简体   繁体   中英

Having trouble adding objects to NSMutableArray

Im having truble adding objects to my 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. However I can't figur out how to add the 2 different objects to my 2 different 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:

*** 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. 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. This the role of NSNull.

Must test to see if the parser returns nil, and if so add [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.

You have to replace

[arrayLabel addObject:labelTitle];

with

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

and

[arraySummary addObject:labelSummary];

with

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

If you really need to include a nil object, then use NSNull.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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