每当找不到 valueForKeyPath 时防止应用程序崩溃?
我正在处理一个正在尝试解析的 _NSDictionary。我正在使用这段代码
NSDictionary *nextArray = [_classDictionary
valueForKeyPath:@"response.page_records.page_record"];
for (NSDictionary *roster2 in nextArray) {
[pageName addObject:[roster2 objectForKey:@"title"]];
[pageID addObject:[roster2 objectForKey:@"id"]];
}
问题是这个 NSDictionary 是从服务器转换的 XML 数据,有时这个数据有一个带有“title”键的对象,有时则没有。每当服务器发送没有标题键(也没有键路径)的数据时,我的应用程序就会崩溃,并且出现 valueForKeyPath 无法找到错误。有没有办法防止抛出这个错误?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在字典上使用 allKeys 方法来转储所有存在的键,然后检查特定键:
You can use the allKeys method on the dictionary to dump all the keys present and then check for the specific key: