2013-07-02 50 views
4

的所有內容我有一個NSArrayNSDictionary,並試圖用下面的代碼刪除重複:IOS 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 *results=[[NSMutableArray alloc]initWithArray: [people valueForKeyPath:@"@distinctUnionOfObjects.state"]]; 
NSLog(@"results %@", results); 

這是輸出我從NSLog的獲得:

results (
    california, 
    michigan, 
    "new york" 
) 

我的問題是如何將完整的目錄添加到數組?

+3

你會期望的結果遏制?你想爲國家賦予獨特的價值,所以對於加利福尼亞州來說應該是阿諾德還是沃茲? – wattson12

回答

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; 
    } 
)