Why @(NO) isn't kind of class NSNumber [closed]

三世轮回 提交于 2021-01-28 12:41:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!