简体   繁体   English

如何在Objective-C中检查有效对象?

[英]How to check for valid object in Objective-C?

I have inherited code that parses from a web service and fills in a NSDictionary . 我继承了从Web服务解析并填写NSDictionary Under some circumstances, which I am going to explore, the parser returns a NSDictionary with count of 5, but the objects are invalid. 在我将要探索的某些情况下,解析器返回一个计数为5的NSDictionary ,但对象无效。 Any message sent to them fails with unrecognized selector, even isKindOfClass: fails. 发送给它们的任何消息都会因无法识别的选择器而失败,甚至isKindOfClass:也会失败。

When I po the object in console, I see this: 当我控制台中的对象,我看到这一点:

error: Execution was interrupted, reason: Attempted to dereference an invalid
ObjC Object or send it an unrecognized selector.
The process has been returned to the state before expression evaluation.

How can I check that the object is invalid, if isKindOfClass: does not work here? 如果isKindOfClass:在这里不起作用,我如何检查对象是否无效?

Here is the output from the console during the crash. 这是崩溃期间控制台的输出。 You see dictionary with 5 empty objects, po on object 9 returns the invalid message. 你看到有5个空对象的字典,对象9上的po返回无效消息。

在此输入图像描述

Here is the po of the big dictionary: 这是大词典的po:

在此输入图像描述

I hope I will be able to check the issue in the parser, but I am also interested in how can I check for that invalid object to prevent the crash. 我希望我能够在解析器中检查问题,但我也对如何检查该无效对象以防止崩溃感兴趣。

The problem is that you are trying to access an element of dictionary using an integer, if the object is a dictionary, the key should be any obj-c object that comforms to copy protocol. 问题是您尝试使用整数访问字典元素,如果对象是字典,则键应该是符合复制协议的任何obj-c对象。 You are using 0 as an integer index, primitive types aren't obj-c objects, you should wrap it into an NSNumber . 您使用0作为integer索引,原始类型不是obj-c对象,您应该将其包装为NSNumber
The other issue is that the NSJSONSerializer returns an id type object, basing on the structure of the parsed JSON this could be a dictionary or an array, you should always inspect the returned object to check the type. 另一个问题是NSJSONSerializer返回一个id类型对象,基于解析的JSON的结构,这可能是一个字典或一个数组,你应该总是检查返回的对象来检查类型。 I usually always expect an arrays of dictionaries, if the system returns just a dictionary, I create an array on the fly with just that object. 我通常总是期望一个字典数组,如果系统只返回一个字典,我只需要那个对象即可创建一个数组。

your po wants an array - but it is a dictionary. 你的宝想要一个数组 - 但它是一本字典。

this wont work 这不行

a dictionary can not be indexed with integers as it doesnt have objectForSubscriptIndex 字典不能用整数索引,因为它没有objectForSubscriptIndex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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