10

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");
}
Lorenzo Ang
  • 1,202
  • 3
  • 12
  • 35

4 Answers4

27

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 ){

} 
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
1
Target *t = self.skill.target;
t = nil;

if (t) {
    NSLog(@"t is Not nil");
}
if (!t) {
    NSLog(@"t is nil");
}
Saif
  • 2,678
  • 2
  • 22
  • 38
1

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)
{
}
Community
  • 1
  • 1
Tomer
  • 3,149
  • 23
  • 26
0

The if operation checks nillable so this should works:

Target *t = self.skill.target;
if (t) {
    NSLog(@"Not nil");
}else{
    NSLog(@"nil");
}

Hope it helps.

sabadow
  • 5,095
  • 3
  • 34
  • 51