我有一个 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];
现在personsArray 包含3 个Person 对象。
我们可以按年龄或名字等属性对这些对象进行分组吗?
我的预期结果是
NSDictionary {
"John" = >{
personObj1, //(Its because personObj1 firstName is John )
personObj2 //(Its because personObj2 firstName is John )
},
"David" = >{
personObj3, //(Its because personObj3 firstName is David )
},
}
我知道我可以通过创建一个 NSDictionary 然后遍历 personArray 来获得这个结果,然后首先检查每个
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.
但是有没有更好的办法呢?
如果我使用 @distinctUnionOfObjects
,我只能按字符串对象分组(不是这样的自定义对象。我说的对吗?)。
感谢您提前回答。