Grupowanie obiektów niestandardowych w Objective-C

Mam i szereg obiektów niestandardowych klasy osobowej

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

NSMutableArray *personsArray = [NSMutableArray array];
Person  *personObj1 =  [[[Person alloc]  init] autorelease];
personObj1.firstName = @"John";
personObj1.lastName = @"Smith";
personObj1.age = @"25";
[personsArray addObject: personObj1];

Person  *personObj2 =  [[[Person alloc]  init] autorelease];
personObj2.firstName = @"John";
personObj2.lastName = @"Paul";
personObj2.age = @"26";
[personsArray addObject: personObj2];

Person  *personObj3 =  [[[Person alloc]  init] autorelease];
personObj3.firstName = @"David";
personObj3.lastName = @"Antony";
personObj3.age = @"30";
[personsArray addObject: personObj3];

Teraz personsArray zawiera 3 obiekty obiektów Person.

Czy możemy zgrupować te obiekty według atrybutu, takiego jak wiek lub imię?

Moim oczekiwanym rezultatem jest

NSDictionary {
    "John" = >{
        personObj1, //(Its  because personObj1 firstName is John )
        personObj2 //(Its  because personObj2 firstName is John )
    },
    "David" = >{
        personObj3, //(Its  because personObj3 firstName is David )
    },
}

Wiem, że mogę uzyskać ten wynik, tworząc NSDictionary, a następnie Iteruj przez personsArray, a następnie sprawdzaj najpierw każdy

NSMutableDictionary *myDict = [NSMutableDictionary dictionary];

  for (Person *person in personsArray){

    if([myDict objectForKey: person.firstName]){
        NSMutableArray *array = [myDict objectForKey: person.firstName];
        [array addObject:person];
        [myDict setObject: array forKey:person.firstName];
    }else{
        NSMutableArray *array = [NSMutableArray arrayWithObject:person];
        [myDict setObject: array forKey:person.firstName];
    }
    }

    NSLog(@"myDict %@", myDict);

//Result myDict will give the desired output. 

Ale czy jest lepszy sposób na to?

Jeśli używam@distinctUnionOfObjects , Mogę grupować tylko obiekty łańcuchowe (Nie takie niestandardowe obiekty. Czy mam rację?).

Z góry dziękuję za odpowiedź.

questionAnswers(6)

yourAnswerToTheQuestion