NSDictionary如何处理NIL对象? [英] How does NSDictionary handle NIL objects?
问题描述
请考虑以下代码.本质上,我们得到2个字符串,然后将这些值添加到NSDictionary.
Consider the code below. In essence, we get 2 strings, then we add these values to the NSDictionary.
但是,我遇到了一个奇怪的错误.当fbAccessTokenKey为0x0(或nil)时,则不会同时添加twitterToken.
However, i hit a weird bug. When fbAccessTokenKey is 0x0 (or nil), then twitterToken would not be added as well.
NSString *fbAccessTokenKey=[[UserStockInfo sharedUserStockInfo] getFBAccessTokenKey];
NSString *twitterToken=[[UserStockInfo sharedUserStockInfo] getTwitterAccessTokenKey];
NSDictionary *params= [[NSDictionary alloc] initWithObjectsAndKeys:
fbAccessTokenKey, @"fb_access_token",
twitterToken, @"twitter_access_token",
nil
];
为什么会这样?解决这个问题的一种好方法是什么?
Why is this happening, and what is a good way of resolving this?
推荐答案
nil
用作标记参数结束"列表的哨兵".如果twitterToken
为nil,则运行时将遍历您的参数,一旦到达twitterToken
,它将认为这取决于对象和键列表的末尾.这是由于涉及列表参数的C/Obj-C的实现方式.
nil
is used as a 'sentinel' for marking the "end of arguments" list. If twitterToken
was nil, the runtime would go through your arguments, and once it got to twitterToken
, it would think that it was up to the end of your list of objects and keys. This is due to the way that C/Obj-C is implemented when it comes to list arguments.
另一种安全的方法是使用NSMutableDictionary
,并检查您的值是否为非nil,然后将它们添加到可变字典中,如下所示:
The alternative safe way to do it is to use an NSMutableDictionary
, and check to see if your values are non-nil, then add them to the mutable dictionary like this:
NSString *fbAccessTokenKey = [[UserStockInfo sharedUserStockInfo] getFBAccessTokenKey];
NSString *twitterToken = [[UserStockInfo sharedUserStockInfo] getTwitterAccessTokenKey];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
if (fbAccessTokenKey) [params setObject:fbAccessTokenKey forKey:@"fb_access_token"];
if (twitterToken) [params setObject:twitterToken forKey:@"twitter_access_token"];
有关更多技术信息,有一篇关于可可与爱的好文章: 查看全文