Note that there are some explanatory texts on larger screens.

plurals
  1. POGrouping of Custom Objects in Objective-C
    primarykey
    data
    text
    <p>I have and array of custom objects of Person Class</p> <pre><code>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]; </code></pre> <p>Now personsArray contains 3 objects of Person objects.</p> <p>Can we group this objects by attribute like age or firstName ?</p> <p>My expected result is </p> <pre><code>NSDictionary { "John" = &gt;{ personObj1, //(Its because personObj1 firstName is John ) personObj2 //(Its because personObj2 firstName is John ) }, "David" = &gt;{ personObj3, //(Its because personObj3 firstName is David ) }, } </code></pre> <p>I know I can get this result by creating an NSDictionary and then Iterate through personsArray, then check for each first</p> <pre><code>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. </code></pre> <p>But is there any better way to do ? </p> <p>If I am using <code>@distinctUnionOfObjects</code> , I can group by string objects only (Not such custom objects. Am I right ?).</p> <p>Thanks for the answer in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload