问题
I have a weird behavior which seem due to some intern cooking in iOS.
When I do :
id data1 = @(NO);
if ([data1 isKindOfClass:[NSNumber class]]) {
// doesn't come here.
}
But with @(YES)
it work perfectly.
First I would like to understand why. Second, I would like to know what you would do in my case ? (Since id can be also text).
Answer :
Indeed, @(NO) is a kind a class NSNumber, and my problem was due to some other mistake.
回答1:
Just use @NO
and @YES
for NSNumber
instances that represent NO
and YES
.
Both [@(NO) class]
and [@(YES) class]
give __NSCFBoolean
.
And [@NO class]
and [@YES class]
give __NSCFBoolean
as well.
And in all four cases a check against isKindOfClass:[NSNumber class]
returned true.
回答2:
The output is 'number' and 'number' for me. So both of them is NSNumber.
id no = @(NO);
id yes = @(YES);
if ([no isKindOfClass:[NSNumber class]]) {
NSLog(@"number");
}if ([yes isKindOfClass:[NSNumber class]]) {
NSLog(@"number");
}
回答3:
What you did is called Boxed expression The syntax:
@( <expression> )
If you want NSNumber
value of course you should use @YES
and @NO
like @maddy said.
but if you interested more about boxed expression take a look at this example (from here):
// numbers.
NSNumber *smallestInt = @(-INT_MAX - 1); // [NSNumber numberWithInt:(-INT_MAX - 1)]
NSNumber *piOverTwo = @(M_PI / 2); // [NSNumber numberWithDouble:(M_PI / 2)]
// enumerated types.
typedef enum { Red, Green, Blue } Color;
NSNumber *favoriteColor = @(Green); // [NSNumber numberWithInt:((int)Green)]
// strings.
NSString *path = @(getenv("PATH")); // [NSString stringWithUTF8String:(getenv("PATH"))]
NSArray *pathComponents = [path componentsSeparatedByString:@":"];
来源:https://stackoverflow.com/questions/21633179/why-no-isnt-kind-of-class-nsnumber