gpt4 book ai didi

iphone - 检查 NSNumber 是否为空

转载 作者:太空狗 更新时间:2023-10-30 03:15:02 25 4
gpt4 key购买 nike

如何检查 NSNumber 对象是否为 nil 或为空?

OK nil 很简单:

NSNumber *myNumber;
if (myNumber == nil)
doSomething

但是如果对象已经被创建,但是因为赋值失败而里面没有值,我该如何检查呢?使用这样的东西?

if ([myNumber intValue]==0)
doSomething

是否有像 NSString 这样的通用方法来测试对象是否为空(参见 post)?

示例 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。所以它包含一个任意数字?

最佳答案

NSValue, NSNumber, ... 应该是从一个值创建的,并且总是保持一个值。测试特定值(如 0)仅在它不在您正在使用的有效值范围内时才有效。

在极少数情况下,如果您有一个表示“无效”“未设置” 的值并且您可以'如果不使用 nil(例如使用标准容器),您可以使用 NSNull相反。

在您的第一个示例中,这可能是:

[dict setValue:[NSNull null] forKey:@"emptyValue"];

if ([dict objectForKey:@"emptyValue"] == [NSNull null]) {
// ...
}

但请注意,除非您需要区分 nil(即不在容器中)和比方说“无效”:

if ([dict objectForKey:@"nonExistent"] == nil) {
// ...
}

至于第二个例子-intValue 给你 0 - 但只是因为发送消息到 nil返回 0。你也可以获得 0 例如对于 NSNumber,其 intValue 之前设置为 0,这可能是一个有效值。
正如我在上面已经写过的,如果 0 对你来说不是一个有效值,你只能做这样的事情。请注意对您来说,什么最有效完全取决于您的要求。

让我尝试总结:

选项 #1:

如果您不需要数字范围内的所有值,您可以使用一个(0-1 或 ...)和 -intValue /... 来具体表示“空”。这显然不是你的情况。

选项#2:

如果容器中的值“空”,您根本不会存储或删除容器中的值:

// add if not empty:
[dict setObject:someNumber forKey:someKey];
// remove if empty:
[dict removeObjectForKey:someKey];
// retrieve number:
NSNumber *num = [dict objectForKey:someKey];
if (num == nil) {
// ... wasn't in dictionary, which represents empty
} else {
// ... not empty
}

然而,这意味着空键与从不存在或非法的键之间没有区别。

选项 #3:

在极少数情况下,将所有键保留在字典中并用不同的值表示“空”会更方便。如果您不能使用数字范围内的一个,我们必须放入不同的内容,因为 NSNumber 没有 “空” 的概念。 Cocoa 已经为这种情况提供了 NSNull:

// set to number if not empty:
[dict setObject:someNumber forKey:someKey];
// set to NSNull if empty:
[dict setObject:[NSNull null] forKey:someKey];
// retrieve number:
id obj = [dict objectForKey:someKey];
if (obj == [NSNumber null]) {
// ... empty
} else {
// ... not empty
NSNumber *num = obj;
// ...
}

此选项现在允许您区分“空”“非空”“不在容器中”(例如非法键)。

关于iphone - 检查 NSNumber 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3716599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com