I am getting an array with null value. Please check the structure of my array below:
(
"< null>"
)
When I'm trying to access index 0 its crashing because of
-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70
Currently its crashing because of that array with a crash log:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70'
*** First throw call stack:
(0x2d9fdf53 0x3820a6af 0x2da018e7 0x2da001d3 0x2d94f598 0x1dee57 0x1dfd31 0x302f598d 0x301a03e3 0x3052aeed 0x3016728b 0x301659d3 0x3019ec41 0x3019e5e7 0x30173a25 0x30172221 0x2d9c918b 0x2d9c865b 0x2d9c6e4f 0x2d931ce7 0x2d931acb 0x3262c283 0x301d3a41 0xabb71 0xabaf8)
libc++abi.dylib: terminating with uncaught exception of type NSException
A lot of good and interesting answers have been given already and (nealry) all of them work.
Just for completion (and the fun of it):
[NSNull null] is documented to return a singleton. Therefore
works fine too.
However, as this is an exception I don't think that using == for comparing objects is a good idea in general. (If I'd review your code, I'd certainly comment on this).
In Swift (or bridging from Objective-C), it is possible to have
NSNull
andnil
in an array of optionals.NSArray
s can only contain objects and will never havenil
, but may haveNSNull
. A Swift array ofAny?
types may containnil
, however.To check against
NSNull
, useis
to check an object's type. This process is the same for Swift arrays andNSArray
objects:You can also use an
if let
orguard
to check if your object can be casted toNSNull
:or
Consider this approach:
Option 1:
Option 2:
Awww, guys. This is an easy one.
I'm sure there are better answers, but this one works.
I found the code for working with
NSNull
has the following problems:So I created the following category:
With the implementation:
It works by the following rules:
Class
(ie singleton instance of theClass
type) then behavior is undefined. However, a method declared in a subclass is allowed to override a category method in its super-class.This allows for more terse code:
. . as opposed to having extra lines to check for
NSNull
. Thezz_
prefix looks a little ugly but is there for safety to avoid namespace collisions.