从数组中获取字符串以应用于标签

get string from array to apply to labels

我正在获取 json 个对象。然后过滤到一个对象,这导致一个对象的数组。这是一个例子:

company
companyname: richs diner
state: iowa
city: antioch

company
companyname: dines
state: california
city: LA

我将以上筛选为一家公司。 然后过滤以仅将城市应用于标签,但您似乎无法将单词数组更改为字符串。

我想将每个值应用到一个标签。但我收到以下错误。 有什么想法吗?

示例代码如下:

     - (void)fetchedData:(NSData *)responseData {

//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData //1
                      options:kNilOptions
                      error:&error];

NSArray* getCompaniesArray = [json objectForKey:@"CompaniesCD"]; //2  get all company info

//NSDictionary* getCompaniesArray = [json objectForKey:@"CompaniesCD"]; //2  get all company info convert to dictionary insted

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"companyName = %@", selectedCompany];//added create filter to only selected state


NSArray *filteredArray = [getCompaniesArray filteredArrayUsingPredicate:predicate];//apply the predicate filter on the array


NSString *city = [filteredArray valueForKey:@"entityformSubmissionID"]; //print array to the string  //error
//NSString *city = [filteredArray objectAtIndex:0];//error
//NSString *city = filteredArray[0];//error

NSLog(@"here is your result: %@", city);//return result.  Works just fine

cityLabel.text = city;  //this does not apply the string to the label results in error

    }

我的错误是:

[__NSArrayI length]: unrecognized selector sent to instance 0x7fea5405f960 2015-12-28 21:49:58.027 J[3203:933300] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x7fea5405f960'

访问带索引的数组。你不能用键访问数组吗?

NSString *city = filteredArray[0];//index 0 or other index 
cityLabel.text = city; 

在这一行中……:

NSString *city = [filteredArray valueForKey:@"entityformSubmissionID"]; //print array to the string  //error

…你假设 valueForKey: 发送到一个数组 returns 一个字符串。这是错误的。它 return 是一个对象数组,这些对象由数组中具有键 entityformSubmissionID 的对象持有。好吧,这听起来比实际情况要复杂。 (如果你在问题中添加了一个例子,解释起来会更容易。)

假设数组的成员是字典。每个字典都为键 entityformSubmissionID 存储了一个值。然后你会得到一个键的数组。

示例:

// The filtered array with 4 objects (dictionaries)
[
  // The first object
  {
    @"entityformSubmissionID" : @"A",
    …
  },
  {
    @"entityformSubmissionID" : @"B",
   …
  },
  {
    @"entityformSubmissionID" : @"C",
    …
  },
  {
    @"entityformSubmissionID" : @"D",
    …
  }
]

应用 valueForKey: 将 return ID 数组:

[
  @"A",
  @"B",
  @"C",
  @"D"
]

这显然不是字符串。您可以选择以下值之一:

NSString *cities = [filteredArray valueForKey:@"entityformSubmissionID"]; 
if( [cities count] > 0 )
{
  cityLabel.text = cities[0];
}