开发者

Can I insert an object into an NSDictionary?

I am pulling in a list of coordinates from our web server. I'm storin开发者_JAVA百科g the whole list as an NSDictionary. While I am using the data (lat, long, radius, name) I would like to update the list of data with 1 or 2 more fields. Is there a way to insert these 2 items to the existing dictionary?

My only existing thought is that I would have to load the data into an NSMutableDictionary to allow additions and just create the new dictionary and overwrite the existing one with the new updated data. Hoping for a simpler or cleaner way rather than ghetto rigging it. Thanks in advance.


From the docs:

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values.

So, NSDictionary is immutable--you may not add to it. Using an NSMutableDictionary is not unclean or "ghetto rigging"...this is the whole purpose for an NSMutableDictionary.


Your thought is correct, you have to create an NSMutableDictionary, as the NSDictionary can not be modified.

NSMutableDictionary *newDoc = [[NSMutableDictionary alloc] initWithDictionary:doc];

If you have any immutable arrays or dictionaries in the NSDictionary, you might need a deep copy for modifcations.

NSMutableDictionary *newDoc = (NSMutableDictionary *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, doc, kCFPropertyListMutableContainers);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜