我有NSArray
NSDictionary
并尝试使用以下代码删除重复:
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"
)
我的问题是如何将完整目录添加到数组中?
答案 0 :(得分:2)
@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;
}
)