简体   繁体   中英

How to check for valid object in Objective-C?

I have inherited code that parses from a web service and fills in a NSDictionary . Under some circumstances, which I am going to explore, the parser returns a NSDictionary with count of 5, but the objects are invalid. Any message sent to them fails with unrecognized selector, even isKindOfClass: fails.

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?

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.

在此输入图像描述

Here is the po of the big dictionary:

在此输入图像描述

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. You are using 0 as an integer index, primitive types aren't obj-c objects, you should wrap it into an 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. 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

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