iOS:为什么我不能将nil设置为NSDictionary值?

app*_*eak 43 iphone null nsdictionary ios

这可能是一个非常基本的问题,但我想知道为什么我不能将nil指定为NSDictionary值?我在我的代码中有很多地方.如果[q objectForKey:@"text"]是零,那么App正在崩溃.

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:2];
[dict setObject:[q objectForKey:@"text"] forKey:@"text"];
Run Code Online (Sandbox Code Playgroud)

在将其分配给字典之前,我必须检查无处不在的nil.这是唯一正确的做法吗?我错过了一些明显的东西吗

if([q objectForKey:@"text"] != nil)
    [dict setObject:[q objectForKey:@"text"] forKey:@"text"];
else
    [dict setObject:@"" forKey:@"text"];
Run Code Online (Sandbox Code Playgroud)

tyb*_*103 65

它想要一个实际的对象......使用NSNull

  • @AppleDeveloper它不会是真的,你将不得不检查`[NSNull null]` (3认同)
  • @AppleDeveloper,因为你不能在`NSDictionary`中存储`nil`,检查它是否已经过时,因为它不可能发生.所以,不,不要检查`nil`,只检查`[NSNull null]`. (3认同)

Dav*_*ist 49

可以使用nil值设置setValue:forKey但删除密钥.

如果您希望能够设置一个密钥,nil您可以使用setValue:forKey:该密钥,如果将其设置为将删除密钥nil(引自下面的文档).请注意Value而不是Object.

setValue:forKey:

将给定的键值对添加到字典中.

...
Run Code Online (Sandbox Code Playgroud) 讨论

此方法使用值向字典添加值和键setObject:forKey:,除非值nil在此情况下该方法尝试使用删除键removeObjectForKey:.

当您稍后尝试使用objectForKey:通过将其设置为已删除的密钥来使用该对象时,nil您将nil返回(请参阅下面的文档).

返回值:

与aKey关联的值,如果没有值与aKey关联,则为nil.

注意:密钥实际上不会出现在字典中,因此无法使用allKeys; 或者被列举.

  • @AppleDeveloper据我所知,字典有自己的setValue实现.NSMutableDictionary文档(在我的回答中链接)没有说明没有使用它:"`setValue:forKey:`将一个给定的键值对添加到字典中....**讨论**这个方法增加了值和键使用`setObject:forKey:`的字典,除非value为nil,否则该方法会尝试使用`removeObjectForKey:`删除键. (4认同)
  • 嗨大卫,感谢您提供有用的信息,但我在Apple文档中读到,您只将setValue用于KVO和普通键值对,您应该始终使用setObject!那不是真的吗? (3认同)

Sam*_*Sol 5

您可以通过以下方式设置nil对象:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

dictionary[@“key”] = nil;
Run Code Online (Sandbox Code Playgroud)

你注意到了吗?

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

/* this statement is safe to execute    */

dictionary[@“key”] = nil;

/* but this statement will crash application    */

[dictionary setObject:nil forKey:@"key"];
Run Code Online (Sandbox Code Playgroud)