我有一个带有NSDictionary的NSArray并尝试使用以下代码删除重复:
NSDictionary *arnold = @{@"name" : @"arnold", @"state" : @"california"};
NSDictionary *jimmy = @{@"name" : @"jimmy", @"state" : @"new york"};
NSDictionary *henry = @{@"name" : @"henry", @"state" : @"michigan"};
NSDictionary *woz = @{@"name" : @"woz", @"state" : @"california"};
NSArray *people = @[arnold, jimmy, henry, woz];
NSMutableArray *results=[[NSMutableArray alloc]initWithArray: [people valueForKeyPath:@"@distinctUnionOfObjects.state"]];
NSLog(@"results %@", results);
这是我从nslog获得的输出:
results (
california,
michigan,
"new york"
)
我的问题是如何将完整的目录添加到数组?
最佳答案 @distinctUnionOfObjects将仅返回指定该属性的唯一对象值,而不返回对象本身.
你可以试试这个:
NSDictionary *arnold = @{@"name" : @"arnold", @"state" : @"california"};
NSDictionary *jimmy = @{@"name" : @"jimmy", @"state" : @"new york"};
NSDictionary *henry = @{@"name" : @"henry", @"state" : @"michigan"};
NSDictionary *woz = @{@"name" : @"woz", @"state" : @"california"};
NSArray *people = @[arnold, jimmy, henry, woz];
NSMutableArray *uniqueArray = [[NSMutableArray alloc] init];
NSMutableSet *checkedStates = [[NSMutableSet alloc] init];
for (NSDictionary *person in people) {
NSString *currentStateName = person[@"state"];
BOOL isDuplicateState = [checkedStates containsObject:currentStateName];
if (!isDuplicateState) {
[uniqueArray addObject:person];
[checkedStates addObject:currentStateName];
}
}
NSLog(@"Results %@", uniqueArray);
NSLog的输出将是:
Results (
{
name = arnold;
state = california;
},
{
name = jimmy;
state = "new york";
},
{
name = henry;
state = michigan;
}
)