我已經和Person類分組對象在Objective-C
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包含Person對象的3個對象的自定義對象的數組。
我們可以通過像age或firstName這樣的屬性對這個對象進行分組嗎?
我預期的結果是
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得到這樣的結果,然後通過personsArray迭代,然後檢查每個第一
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
,我只能按字符串對象進行分組(不是這樣的自定義對象,對吧?)。
感謝您提前回答。
感謝它幫助我,我想要分組的同樣結果。:) –