简体   繁体   中英

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?

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"]];
}

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