繁体   English   中英

如何从NSDictionary中删除对象

[英]how to remove object from NSDictionary

嗨,我有一个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);

在这里,我想删除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")

我发布我的答案,因为我正在寻找相同的问题,并受到@MathieuF的启发

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM