我有以下NSMutableArray,其键为“ id,value,name”和“ id,animal”:
<__NSArrayM 0x7a64f450>(
{
id = ccc;
value = 11;
name = "Greg";
},
{
id = bbb;
value = 2;
name = "Dan";
},
{
id = aaa;
value = 23;
name = "Mary";
},
{
id = aaa;
animal = "dog";
},
{
id = ccc;
animal = "cat";
}
)
是否可以通过匹配键来合并内容?所以最后我会得到:
<__NSArrayM 0x7a64f450>(
{
id = ccc;
value = 11;
name = "Greg";
animal = "cat"
},
{
id = bbb;
value = 2;
name = "Dan";
},
{
id = aaa;
value = 23;
name = "Mary";
animal = "dog";
}
)
我正在寻找如果键匹配id的对象组合。所有其他键应合并在一起。
一个更优雅的方法是使用NSPredicate。使用此代码。arrRecords是您在合并之前存储所有记录的位置。
NSString *strKey;
NSPredicate *predicate;
NSArray *tempArray;
for(int i = 0; i < [arrRecords count]; i++) {
strKey = [[arrRecords objectAtIndex:i] valueForKey:@"id"];
predicate = [NSPredicate predicateWithFormat:@"id == %@",strKey];
tempArray = [arrRecords filteredArrayUsingPredicate:predicate];
if([tempArray count] > 1) {
for(int j =0; j < [tempArray count]-1; j++) {
[[arrRecords objectAtIndex:i] addEntriesFromDictionary:[tempArray objectAtIndex:j+1]];
[arrRecords removeObject:[tempArray objectAtIndex:j+1]]; // You need to remove the record from super set otherwise this will get duplicated again.
}
}
}
编辑-NSDictionary对象的代码
NSMutableArray *newRecords = [[NSMutableArray alloc] init]; // Add this also before method body
for(int i = 0; i < [arrRecords count]; i++) {
strKey = [[arrRecords objectAtIndex:i] valueForKey:@"id"];
predicate = [NSPredicate predicateWithFormat:@"id == %@",strKey];
tempArray = [arrRecords filteredArrayUsingPredicate:predicate];
if([tempArray count] > 1) {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
for(int j =0; j < [tempArray count]; j++) {
[tempDict addEntriesFromDictionary:[tempArray objectAtIndex:j]];
if(j!=0) {
[arrRecords removeObject:[tempArray objectAtIndex:j]];
}
}
[newRecords addObject:tempDict];
}
else {
[newRecords addObject:[arrRecords objectAtIndex:i]];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句