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)
Dav*_*ist 49
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; 或者被列举.
您可以通过以下方式设置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)
| 归档时间: |
|
| 查看次数: |
35893 次 |
| 最近记录: |