Consider the code below. In essence, we get 2 strings, then we add these values to the NSDictionary.
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?
nilis used as a ‘sentinel’ for marking the “end of arguments” list. IftwitterTokenwas nil, the runtime would go through your arguments, and once it got totwitterToken, 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.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:For more technical info, there’s a good article on Cocoa with Love: http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html