Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

enter image description here

Here is the po of the big dictionary:

enter image description here

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.

like image 729
Martin Koles Avatar asked Nov 24 '25 15:11

Martin Koles


2 Answers

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.

like image 159
Andrea Avatar answered Nov 27 '25 03:11

Andrea


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

like image 40
Daij-Djan Avatar answered Nov 27 '25 05:11

Daij-Djan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!