Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is nil in Objective-C? [duplicate]

So I know this seems pretty basic but it doesn't seem to be working for some reason. I have the following code.

Target *t = self.skill.target;


if (![t isEqual:nil]) {
    NSLog(@"Not nil");
}

I tried this and it comes up as not nil everytime which is great except for when t should actually be nil. I even tried putting variation into the code like so and my t is still coming up as not nil for some reason. Am I doing something wrong? :\

Target *t = self.skill.target;
t = nil;

if (![t isEqual:nil]) {
    NSLog(@"Not nil");
}
like image 312
Lorenzo Ang Avatar asked Mar 04 '15 10:03

Lorenzo Ang


People also ask

What is Nsnull?

A singleton object used to represent null values in collection objects that don't allow nil values.

What does nullable mean in Objective C?

nonnull : the value won't be nil. It bridges to a Swift regular reference. nullable : the value can be nil. It bridges to a Swift optional. null_resettable : the value can never be nil when read, but you can set it to nil to reset it.


3 Answers

You can do it normally just by checking the object itself. There is also a good explanation on NSHipster for NSNull.

if( myObject ){
    // do something if object isn't nil
} else {
    // initialize object and do something
}

otherwise just use

if( myObject == nil ){

} 
like image 193
Alex Cio Avatar answered Oct 04 '22 11:10

Alex Cio


Target *t = self.skill.target;
t = nil;

if (t) {
    NSLog(@"t is Not nil");
}
if (!t) {
    NSLog(@"t is nil");
}
like image 43
Saif Avatar answered Oct 04 '22 13:10

Saif


As this answer says:

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result.

So, a nil object is special. you can't compare it using the isEqual method. you should compare it without sending it a message, like this:

if (t) 
{
}

or simply:

if (t != nil)
{
}
like image 34
Tomer Avatar answered Oct 04 '22 12:10

Tomer