Grouping of Custom Objects in Objective-C

前端 未结 6 1641
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 03:59

I have and array of custom objects of Person Class

Person : NSObject{
    NSString *firstName;
    NSString *lastName; 
    NSString *age;
}

NSMutableArray          


        
6条回答
  •  滥情空心
    2021-01-12 04:51

    Checkout this answers it is very similar to what you want

    https://stackoverflow.com/a/15375756/1190861

    The code in your case will be as the following:

    NSMutableDictionary *result = [NSMutableDictionary new];
    
    NSArray *distinctNames;
    distinctNames = [personsArray valueForKeyPath:@"@distinctUnionOfObjects.firstName"];
    for (NSString *name in distinctNames) {
        NSPredicate predicate = [NSPredicate predicateWithFormat:@"firstName = %@", name]; 
        NSArray *persons = [personsArray filteredArrayUsingPredicate:predicate];
        [result setObject:persons forKey:name];
    }
    
    NSLog(@"%@", result);
    

提交回复
热议问题