NSDictionary如何处理NIL对象?

min*_*eow 5 objective-c nsdictionary ios

请考虑以下代码.本质上,我们得到2个字符串,然后我们将这些值添加到NSDictionary.

但是,我遇到了一个奇怪的错误.当fbAccessTokenKey为0x0(或nil)时,也不会添加twitterToken.

NSString *fbAccessTokenKey=[[UserStockInfo sharedUserStockInfo] getFBAccessTokenKey];
NSString *twitterToken=[[UserStockInfo sharedUserStockInfo] getTwitterAccessTokenKey];

NSDictionary *params= [[NSDictionary alloc] initWithObjectsAndKeys:
                       fbAccessTokenKey, @"fb_access_token", 
                       twitterToken, @"twitter_access_token", 
                       nil
                       ];
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况,解决这个问题的好方法是什么?

Nic*_*rge 14

nil用作标记"参数结束"列表的"哨兵".如果twitterToken是nil,运行时将通过你的参数,一旦它到达twitterToken,它会认为它是在你的对象和键列表的末尾.这是由于C/Obj-C在列表参数方面的实现方式.

另一种安全的方法是使用a NSMutableDictionary,并检查你的值是否为非零,然后将它们添加到可变字典中,如下所示:

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"];
Run Code Online (Sandbox Code Playgroud)

有关更多技术信息,有一篇关于Cocoa with Love的好文章:http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html