我试图根据值数组操作一个字典数组。
例如:
arrayOfDicts =
(
{
caption = a;
urlRep = "12";
},
{
caption = b;
urlRep = "34";
},
{
caption = c;
urlRep = "56";
}
)
值数组:
urlReps = (12,56);
我想要实现的结果:
(
{
caption = a;
urlRep = "12";
},
{
caption = c;
urlRep = "56";
}
)
我现在根据数组添加的代码是:
NSMutableArray *arrayOfDicts;
NSMutableSet *urlReps;
[urlReps minusSet:[NSSet setWithArray:[arrayOfDicts valueForKey:@"urlRep"]]];
// merge new dicts to the original array
for (id urlRep in urlReps)
{
[arrayOfDicts addObject:@{ @"urlRep" : urlRep, @"caption" : @"" }];
}
这增加了我的数组,如果数组中有更多的url,但是如果数组中的url与dict相比,我还需要删除
答案 0 :(得分:1)
尝试使用NSPredicate来过滤数组:
NSArray *arrayOfDicts = .... //your existing data
NSArray *filteredURLParams = @[@"12",@"56"];
NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"urlRep IN %@",filteredURLParams];
NSArray *filteredDicts = [arrayOfDicts filteredArrayUsingPredicate:urlPredicate];
答案 1 :(得分:0)
这是一些老式的,直截了当的,完全未经测试的代码: - )
// Your data
NSMutableArray* arrayOfDicts = [...];
NSMutableSet* urlReps = [...];
// Will receive those dictionaries that have a matching urlRep
NSMutableArray* filteredArrayOfDicts = [NSMutableArray arrayWithCapacity:0];
// Initially contains all urlReps, but we will successively
// eliminate those urlReps that we encountered
NSMutableSet* urlRepsNotSeen = [NSMutableSet setWithCapacity:0];
[urlRepsNotSeen addObjects:[urlReps allObjects]];
for (NSDictionary* dict in arrayOfDicts)
{
NSString* urlRep = [dict valueForKey:@"urlRep"];
if ([urlReps containsObject:urlRep])
[
[filteredArrayOfDicts addObject:dict];
// Not sure what happens if urlRepsNotSeen does not contain the
// urlRep (because we eliminated it earlier). If it crashes, add
// this check:
// if ([urlRepsNotSeen containsObject:urlRep])
[urlRepsNotSeen removeObject:urlRep];
}
arrayOfDicts = filteredArrayOfDicts;
for (NSString urlRepNotSeen in urlRepsNotSeen)
{
[arrayOfDicts addObject:@{ @"urlRep" : urlRepNotSeen, @"caption" : @"" }];
}