简体   繁体   English

将对象添加到NSMutableArray时遇到问题

[英]Having trouble adding objects to NSMutableArray

Im having truble adding objects to my 2 NSMutableArrays. 我在将对象添加到我的2个NSMutableArrays中很麻烦。 The data comes from a database and I know that my parsing is correct because I get valid outputs when I use the NSLog. 数据来自数据库,我知道我的解析是正确的,因为当我使用NSLog时会得到有效的输出。 However I can't figur out how to add the 2 different objects to my 2 different NSMutableArrays. 但是我无法弄清楚如何将2个不同的对象添加到2个不同的NSMutableArrays中。 Here is my code 这是我的代码

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

     allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
     feed = [allDataDictionary objectForKey:@"feed"];
     arrayOfEntry = [feed objectForKey:@"entry"];

     for (NSDictionary *dictionary in arrayOfEntry) {

         NSDictionary *title = [dictionary objectForKey:@"title"];
         NSString     *labelTitle = [title objectForKey:@"label"];

         [arrayLabel addObject:labelTitle];

         NSDictionary *summary = [dictionary objectForKey:@"summary"];
         NSString     *labelSummary = [summary objectForKey:@"label"]; 

         [arraySummary addObject:labelSummary]; //This line makes the application crash

     }

}

for some reason when I want to add labelSummary to arraySummary I get this error: 由于某些原因,当我想将labelSummary添加到arraySummary时,出现此错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

Any help is appreciated. 任何帮助表示赞赏。

Your parsing is indeed correct. 您的解析确实是正确的。 However, when the parser comes across an empty field it returns nil. 但是,当解析器遇到一个空字段时,它将返回nil。 The problem is the that NSArrays cannot accept nils, because nil is not an object, it's equivalent to 0. Therefore, you most add an object. 问题在于NSArrays无法接受nils,因为nil不是对象,它等于0。因此,您最多添加一个对象。 This the role of NSNull. NSNull的作用。

Must test to see if the parser returns nil, and if so add [NSNull null]. 必须测试以查看解析器是否返回nil,如果是,则添加[NSNull null]。

NSString* labelSummary = [summary objectForKey:@"label"]; 

[arraySummary addObject:(labelSummary!=nil)?labelSummary:[NSNull null];

The error message tells you that one of the objects you are trying to add to the array is nil. 该错误消息告诉您您要添加到数组中的对象之一为nil。

You have to replace 你必须更换

[arrayLabel addObject:labelTitle];

with

if (labelTitle != nil) {
   [arrayLabel addObject:labelTitle];
}

and

[arraySummary addObject:labelSummary]; [arraySummary addObject:labelSummary];

with

if (labelSummary != nil) {
   [arraySummary addObject:labelSummary];
}

If you really need to include a nil object, then use NSNull. 如果确实需要包含nil对象,则使用NSNull。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM