I have an array of custom objects of class Person
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];
Now personArray contains 3 objects of Person objects.
Is it possible to group objects by an attribute of type age or firstName?
Expected Result
NSDictionary { "John" = >{ personObj1, //(Its because personObj1 firstName is John ) personObj2 //(Its because personObj2 firstName is John ) }, "David" = >{ personObj3, //(Its because personObj3 firstName is David ) }, }
I know that I can get this result by creating an NSDictionary and then Iterate through personArray and then checking every first
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);
But is there a better way to do this?
If I use @distinctUnionOfObjects , I can only group string objects (Not such user objects. Right?).
Thanks for the reply in advance.
objective-c iphone cocoa
SP
source share