按属性排序NSManagedObjects的NSSet

时间:2010-12-16 21:26:43

标签: iphone objective-c cocoa-touch core-data

如果NSSet包含具有名为NSManagedObject的字符串属性的子类name的对象,我该如何按名称对该集进行排序?这是我使用NSPredicate吗?

谢谢!

2 个答案:

答案 0 :(得分:33)

不,但您使用的是NSSortDescriptor

你可以像这样使用sortedArrayUsingDescriptors:方法:

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sorted = [yourSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

答案 1 :(得分:5)

通过提及NSPredicate,我觉得OP想要将集合作为执行获取的一部分进行排序。无论他是否意味着这一点,这都是一个例子。假设您在Employee实体和Department实体之间存在多对反关系,即某个部门包含许多员工。鉴于您已经获取了部门,请获取部门中的员工并按名字对其进行排序:

使用MagicalRecord:

Department *department = someFetchedDepartment; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", department];
NSArray *sortedEmployees = [Employee MR_findAllSortedBy:@"firstName" ascending:YES withPredicate:predicate];

没有MagicalRecord:

NSFetchRequest *request = [[NSFetchRequest alloc] init];    

NSEntityDescription *employeeEntity = [NSEntityDescription @"Employee" inManagedObjectContext:self.context];
[request setEntity:employeeEntity];

Department *department = someFetchedDepartment; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", department];
[request setPredicate:predicate];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:ascending];
[request setSortDescriptors:@[sortDescriptor]];

NSError *error = nil;
NSArray *sortedEmployees = [self.context executeFetchRequest:request error:&error];