编辑:更好的例子...合并一个NSArray成的NSSet和避免对iphone在Objective-C复制
所以我有“现有”对象的的NSMutableSet,我想下载JSON数据,解析它,并将这些新对象与我现有的对象合并,使用新下载的对象更新任何重复对象。下面是现有的一组对象的样子:
NSArray *savedObjects = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"1", @"id", @"hello there", @"body", @"200", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"2", @"id", @"hey now", @"body", @"10", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"3", @"id", @"welcome!", @"body", @"123", @"score", nil],
nil
];
self.objects = [NSMutableSet setWithArray:savedObjects];
// after downloading and parsing JSON... I have an example array of objects like this:
NSArray *newObjects = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"1", @"id", @"hello there", @"body", @"9999", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"4", @"id", @"what's new", @"body", @"22", @"score", nil],
nil
];
因此,例如,合并这个新的对象之后,ID为1的对象将现在的9999分和ID为4的新对象将被添加到集合。
我真的想避免循环每个新对象的NSMutableSet只是为了检查@“id”属性存在......我想我可以使用addObjectsFromArray来合并这些新的对象,但它看起来像是因为属性不同(例如:分数:9999)它不会将新对象看作集合中的现有对象。
我使用的数字作为字符串来简化这个例子。我也想避免使用仅适用于iOS SDK 4.0的功能,因为该应用将与3.0兼容。
谢谢!我很感激!
为什么要构建一个NSArray并立即转换是一个NSSet中?您应该直接为保存的对象使用'[NSSet setWithObjects:...]'。 – 2010-10-28 22:43:15
哦,好吧,我想我不得不因为他们以前也是JSON。 setWithObjects在传递数组时是否工作?谢谢。 – taber 2010-10-28 22:53:39
'+ [NSSet中setWithObjects:]'工作就像'+ [NSArray的arrayWithObjects:]'不同之处在于它返回一个集而不是阵列。 – 2010-10-29 01:01:35