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

时间:2015-12-29 06:02:12

标签: objective-c nsstring uilabel nsarray

我正在获取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]:发送到实例的无法识别的选择器   0x7fea5405f960 2015-12-28 21:49:58.027 J [3203:933300] ***终止   应用程序由于未捕获的异常' NSInvalidArgumentException',原因:   ' - [__ NSArrayI length]:发送到实例的无法识别的选择器   0x7fea5405f960'

2 个答案:

答案 0 :(得分:0)

使用索引访问数组。你无法使用密钥访问数组。

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

答案 1 :(得分:0)

在这一行......:

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

...您假设发送到数组的valueForKey:返回一个字符串。这是错的。它返回一个对象数组,这些对象由数组中的对象持有,键为entityformSubmissionID。好吧,这听起来比现在复杂得多。 (如果您在Q中添加了一个示例,那么解释会更容易。)

假设数组的成员是字典。每个字典都有一个为密钥entityformSubmissionID存储的值。然后你会得到一组那些钥匙。

示例:

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

应用valueForKey:将返回ID数组:

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

这显然不是字符串。您可以选择其中一个值:

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