开发者

How to combine the advantages of `int` and `NSInteger`

开发者 https://www.devze.com 2023-03-31 12:05 出处:网络
A seemingl开发者_如何学运维y simple question: Can I have some sort of Number object, which can be nil but which I can assign like a primitive int:

A seemingl开发者_如何学运维y simple question: Can I have some sort of Number object, which can be nil but which I can assign like a primitive int:

like this:

NSNumber *n = nil; 
n = 3; 

if(n == nil){ 
    // some actions... 
} else if (n == 1){ 
    // some actions... 
} else { 
    // some actions... 
}

Thanks for your input


The answer is NO. If the variable is an object you can either assign another object,

n = anotherNSNumber;

or, set the value by using properties or by methods,

n = [NSNumber numberWithInt:3];

and, compare the object with another object,

if (n == anotherNSNumber) // Checks the reference

or compare its value by using properties/methods,

if (([n intValue] == 3) || ([n intValue] == [anotherNSNumber intValue]))


The short answer as others have mentioned is "No".
But the following slight modification to you code will achieve a similar result:

NSNumber *nObject = [NSNumber numberWithInt:3]; 
int n = nObject.intValue; // Zero if nObject is nil

if(nObject == nil){ 
    // some actions... 
} else if (n == 1){ 
    // some actions... 
} else { 
    // some actions... 
}


Not the way you think you can. No.

when you say:

NSNumber *n = nil;

what you are saying is declare a pointer that points to an NSNumber object, but for now have it point to nil This is okay; because what you might do later is to get a pointer to an NSNumber object and then assign it to this variable so that n is then a pointer no a valid NSNumber object.

With your next line:

n = 3;

You are not assigning a value to the object, but you are saying that n points to the address 3. Which isn't an address and which doesn't contain an object.


No, you can't. The reason for that is that nil is a pointer to the address 0x0 i.e. nil == 0. So you won't be able to disambiguate between 0 and nil.

Not to mention the fact they are also supposed to be different types. nil is used as a pointer whereas a number like 0 or 3 is a scalar.

nil is defined as

#define nil NULL

A typical definition of NULL goes like this:

#define NULL ((void *)0)
0

精彩评论

暂无评论...
验证码 换一张
取 消