NSDictionary objectForKey - 需要一个包含一个元素的 NSArray 而不仅仅是该元素
我是 Objective-C 的新手,需要一些帮助。在下面的代码中,如果 xml 仅包含一个元素,则 objectForKey 调用将生成单个元素,而不是具有一个元素的 NSArray。我应该如何更新代码以确保该行:
[[ApplicationManager sharedInstance] setTags:[[result objectForKey:XML_OPTION_LIST] objectForKey:XML_OPTION]];
始终使用 NSArray 调用 setTags (即使 xml 包含零个或一个元素)?
NSString *XMLResponse = [request responseString];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLResponse error:&parseError];
NSDictionary *result = [xmlDictionary objectForKey:XML_RESULT];
if ([[[result objectForKey:XML_ERROR_CODE] objectForKey:XML_TEXT] isEqualToString:XML_ERROR_NONE]) {
[[ApplicationManager sharedInstance] setTags:[[result objectForKey:XML_OPTION_LIST] objectForKey:XML_OPTION]];
[[ApplicationManager sharedInstance] save];
}
xml OPTION_LIST 元素包含一个或多个 OPTION 元素。当只有一个 OPTION 元素时就会发生错误(超出了此代码的范围)。 我很感激你的帮助。
I'm new to objective-c and need some help. In the code below, if the xml contains only one element, then the objectForKey calls will result in a single element instead of an NSArray with one element. How should I update the code to make sure that the line:
[[ApplicationManager sharedInstance] setTags:[[result objectForKey:XML_OPTION_LIST] objectForKey:XML_OPTION]];
always calls setTags with an NSArray (even if the xml contains zero or one element)?
NSString *XMLResponse = [request responseString];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLResponse error:&parseError];
NSDictionary *result = [xmlDictionary objectForKey:XML_RESULT];
if ([[[result objectForKey:XML_ERROR_CODE] objectForKey:XML_TEXT] isEqualToString:XML_ERROR_NONE]) {
[[ApplicationManager sharedInstance] setTags:[[result objectForKey:XML_OPTION_LIST] objectForKey:XML_OPTION]];
[[ApplicationManager sharedInstance] save];
}
The xml OPTION_LIST element contains one or more OPTION element. It's when there is only one OPTION element that the error occur (outside the scope of this code).
I appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生错误的原因是您尝试将
objectForKey:
消息发送到某个不是NSDictionary
实例的对象。您将包含一个测试来检测这一点,并根据测试结果直接传递该元素的
setTags:
方法。The error occurs because you try to send
objectForKey:
message to some object that isn't anNSDictionary
instance.You would include a test to detect that and pass the
setTags:
method that element directly according to the test result.