如何从NSDictionary中删除对象

您好我有一个NSdictionary,其中我添加一个关键“国家”的数组。 现在我把这个字典的值放到数组中,并按照alpahbatical的顺序对数组进行sorting。现在我想把这个数组添加到我的字典中(也就是我想用新的已sorting数组更新我的字典,并从中删除旧数组)。 ……. 这个怎么做

我的代码如下

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); 

在这里,我想删除countriesToLiveInArray,并用具有相同的键值,即国家在此先感谢sortedArray取代它。

首先你需要使用一个NSMutableDictionary并把这个代码:

 [countriesToLiveInDict removeObjectForKey:@"Countries"]; [countriesToLiveInDict setObject:sortedArray forKey:@"Countries"]; 

首先让你的NSDictionary为NSMutableDictionary,然后写下面的代码行

 [countriesToLiveInDict removeObjectForKey:@"Countries"]; 

这一定会解决你的问题。

NSDictionary不能删除任何东西,请使用NSMutableDictionary ,如下所示:

 NSMutableDictionary *countriesToLiveInDict = [NSMutableDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"]; 

对于Swift 3 @MathieuF回答它首先你需要使用一个NSMutableDictionary并把这个代码:

 countriesToLiveInDict.removeObject(forKey: "Countries") 

我张贴我的答案,因为我是search相同的问题,并获得启发@MathieuF