如何检查 NSNumber 对象是 nil 还是空?
OK nil 很简单:
NSNumber *myNumber;
if (myNumber == nil)
doSomething
但是,如果对象已经创建,但由于分配失败,其中没有值,我该如何检查呢?使用这样的东西?
if ([myNumber intValue]==0)
doSomething
有没有一种通用的方法来测试对象的空性,比如 NSString 可用(见这篇文章)?
示例 1
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSNumber *emptyNumber = [dict objectForKey:@"emptyValue"];
包含哪个值emptyNumber
?如何检查是否emptyNumber
为空?
示例 2
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSString *myString = [dict objectForKey:@"emptyValue"];
if (myString == nil || [myString length] == 0)
// got an empty value
NSNumber *emptyNumber=nil;
如果我在emptyNumber
设置为 nil 后使用它会发生什么?
[emptyNumber intValue]
我会得到零吗?
示例 3
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSNumber *myEmptyValue = [dict objectForKey:@"emptyValue"];
if (myEmptyValue == nil)
// NSLog is never called
NSLog(@"It is empty!");
像这种方式 NSLog 永远不会被调用。myEmptyValue
不是nil
和不是NSNull
。所以它包含一个任意数字?