davis
davis

Reputation: 1951

Prevent app from crashing whenever valueForKeyPath can't be found?

I'm dealing with an _NSDictionary that I'm trying to parse. I'm using this code

NSDictionary *nextArray = [_classDictionary 
valueForKeyPath:@"response.page_records.page_record"];
for (NSDictionary *roster2 in nextArray) {
    [pageName addObject:[roster2 objectForKey:@"title"]];
    [pageID addObject:[roster2 objectForKey:@"id"]];
}

The problem is that this NSDictionary is converted XML data from a server and sometimes this data has an object with the "title" key and sometimes it doesn't. Whenever the server sends data without the title key (and also without the keypath) my app crashes and I get a valueForKeyPath can't be found error. Is there a way to prevent this error from being thrown?

Upvotes: 2

Views: 819

Answers (1)

ennuikiller
ennuikiller

Reputation: 46975

You can use the allKeys method on the dictionary to dump all the keys present and then check for the specific key:

for (NSDictionary *roster2 in nextArray) {
    NSArray *keys = [roster2 allKeys];
    if ([keys containsObject:@"title"]
        [pageName addObject:[roster2 objectForKey:@"title"]];
    [pageID addObject:[roster2 objectForKey:@"id"]];
}

Upvotes: 1

Related Questions