如果NSSet
包含具有名为NSManagedObject
的字符串属性的子类name
的对象,我该如何按名称对该集进行排序?这是我使用NSPredicate
吗?
谢谢!
答案 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];