Testing equality to NSNull

瘦欲@ 提交于 2020-01-23 04:32:05

问题


Below is a code block, that is supposed to test to see if a dictionary is null, and if it isn't, pull out the correct object. However, for some reason, despite the fact that the if check fails, the code still executes. Is there some quirk with how NSNull works that I don't understand, or is this an Apple bug?

if (svcUser && !(svcUser == (id)[NSNull null])) {
    return [svcUser objectForKey:@"access_level"];
}

Console response:

(lldb) print svcUser && !(svcUser == (id)[NSNull null])
(bool) $0 = false
(lldb) continue
-[NSNull objectForKey:]: unrecognized selector sent to instance 0x2b51678

回答1:


Simply check for:

svcUser == [NSNull null]

This is the approach that Apple mentions in their docs.




回答2:


NSNull is a class. And like with all classes, you must use isEqual:, not == to see if two objects represent the same value.

if (svcUser && ![svcUser isEqual:[NSNull null]]) {
    return [svcUser objectForKey:@"access_level"];
}



回答3:


You can check it by using:

 if(![svcUser isKindOfClass:[NSNull class]]){
    return [svcUser objectForKey:@"access_level"];
}



回答4:


Using @JE42's approach gives me a warning as of Xcode 5.1. Instead cast it:

(id)svcUser == [NSNull null]


来源:https://stackoverflow.com/questions/16600350/testing-equality-to-nsnull

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