我有和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对象对象.
我们可以通过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,我只能按字符串对象分组(不是这样的自定义对象.我是对的吗?).
谢谢你提前回答.
解决方法
查看此答案它与您想要的非常相似
https://stackoverflow.com/a/15375756/1190861
您的案例中的代码如下:
NSMutableDictionary *result = [NSMutableDictionary new]; NSArray *distinctNames; distinctNames = [personsArray valueForKeyPath:@"@distinctUnionOfObjects.firstName"]; for (Nsstring *name in distinctNames) { nspredicate predicate = [nspredicate predicateWithFormat:@"firstName = %@",name]; NSArray *persons = [personsArray filteredArrayUsingPredicate:predicate]; [result setobject:persons forKey:name]; } NSLog(@"%@",result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。