如何从NSDictionary中删除对象

V.V*_*V.V 29 iphone objective-c nsdictionary ios

嗨,我有一个NSdictionary我在其中添加一个关键"国家"的数组.现在我把这个字典的值放到数组中并按照alpahbatical顺序对数组进行排序.现在我想将这个数组添加到我的字典中(我想用新的排序数组更新我的字典并从中删除旧数组). ....... 这该怎么做

我的代码如下

NSArray *countriesToLiveInArray = [NSArray arrayWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway", @"New Zealand", @"Greece", @"Italy", @"Ireland", nil];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"];


NSArray *tmpary = [countriesToLiveInDict valueForKey:@"Countries"];
NSLog(@"ary value is  %@",ary);
NSArray *sortedArray = [tmpary sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSLog(@"sortedArray is %@",sortedArray);
Run Code Online (Sandbox Code Playgroud)

在这里,我想删除countriesToLiveInArray并将其替换为具有相同键值的sortedArray,即国家/地区提前感谢..

Mat*_*euF 68

首先你需要使用a NSMutableDictionary并输入以下代码:

[countriesToLiveInDict removeObjectForKey:@"Countries"];
[countriesToLiveInDict setObject:sortedArray forKey:@"Countries"];
Run Code Online (Sandbox Code Playgroud)

  • 您无需删除密钥的上一个对象.-setObject:forKey:如果在已存在的kety上调用,则自动释放上一个对象. (21认同)

Atu*_*ain 5

首先使您的NSDictionary成为NSMutableDictionary然后编写以下代码行

[countriesToLiveInDict removeObjectForKey:@"Countries"];
Run Code Online (Sandbox Code Playgroud)

这肯定会解决您的问题.

  • 设置`countriesToLiveInDict =`是必要的吗? (2认同)