5

我有一个NSArrayNSDictionary尝试使用以下代码删除重复项:

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"
)

我的问题是如何将完整目录添加到数组中?

4

1 回答 1

3

@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;
    }
)
于 2014-06-30T03:19:54.667 回答