G.P. Burdell
G.P. Burdell

Reputation: 161

Difference between an variable set to nil and 0

if (myFloat == nil){
    \\Do Method
}

In the above situation, the method will run only if myFloat is nil. Will it also run if myFloat was set to 0?

Upvotes: 4

Views: 3741

Answers (3)

Jamie Birch
Jamie Birch

Reputation: 6112

Before I get into my answer, see this table from NSHipster for a refresher on the meanings of the family of null-like symbols:

Symbol Value Meaning
NULL (void *)0 literal null value for C pointers
nil (id)0 literal null value for Obj-C objects
Nil (Class)0 literal null value for Obj-C classes
NSNull [NSNull null] singleton object used to represent null

As the value column above shows, all but NSNull have 0 as their underlying value.

I ran a few test cases related to nil-checking and zero-checking.

Key:

  • ✅ condition was satisfied, so the log printed
  • ❌ condition was not satisfied, so the log didn't print
NSNumber* nilNSNumber = nil;
if(nilNSNumber == nil){
    NSLog(@"nilNSNumber == nil"); // ✅
}
if(nilNSNumber == 0){
    NSLog(@"nilNSNumber == 0"); // ✅
}

NSNumber* zeroNSNumberA = 0;
if(zeroNSNumberA == nil){
    NSLog(@"zeroNSNumberA == nil"); // ✅
}

NSNumber* zeroNSNumberB = [[NSNumber alloc] initWithInt:0];
if(zeroNSNumberB == nil){
    NSLog(@"zeroNSNumberB == nil"); // ❌
}
if(zeroNSNumberB == 0){
    NSLog(@"zeroNSNumberB == 0"); // ❌
}

NSObject* objectUninitialised = [NSObject alloc];
if(objectUninitialised == nil){
    NSLog(@"objectUninitialised == nil"); // ❌
}
if(objectUninitialised == 0){
    NSLog(@"objectUninitialised == 0"); // ❌
}

NSObject* objectInitialised = [objectUninitialised init];
if(objectInitialised == nil){
    NSLog(@"objectInitialised == nil"); // ❌
}
if(objectUninitialised == 0){
    NSLog(@"objectInitialised == 0"); // ❌
}

if([NSNull null] == 0){
    NSLog(@"NSNull == 0"); // ❌
}
if([NSNull null] == nil){
    NSLog(@"NSNull == nil"); // ❌
}

Upvotes: 0

mmmmmm
mmmmmm

Reputation: 32720

nil should only be used with pointers. It says that the pointer has not been set to a value.

Floats and other C types just have a value. (Strictly floats and double possibly can have values like NaN but this is more difficult to manage)

In Objective C you can wrap a float in the class NSNumber. An object of this class is referenced by a pointer so a variable of type NSNumber* can be nil.

Upvotes: 1

BobbyShaftoe
BobbyShaftoe

Reputation: 28499

Well, nil is technically 0. However, some of this depends on what type of variable myFloat is. If myFloat is a C float, you can't depend on it being exactly 0. You really should be using nil on id types.

Upvotes: 0

Related Questions