Bil*_*iff 10 iphone cocoa-touch core-data objective-c
如果NSSet
包含的对象是一个NSManagedObject
带有字符串属性的子类name
,则如何按名称对该集进行排序?这是我要用的地方NSPredicate
吗?
谢谢!
Jac*_*kin 33
不,但你会用NSSortDescriptor
.
你可以使用这样的sortedArrayUsingDescriptors:
方法:
NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sorted = [yourSet sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];
Run Code Online (Sandbox Code Playgroud)
通过提及NSPredicate,我觉得OP想要将集合排序为执行获取的一部分.无论他是否意味着这一点,这都是一个例子.假设您在Employee实体和Department实体之间存在多对多关系,即部门包含许多员工.鉴于您已经获取了部门,请获取部门中的员工并按名字对其进行排序:
使用MagicalRecord:
Department *department = someFetchedDepartment;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department == %@", department];
NSArray *sortedEmployees = [Employee MR_findAllSortedBy:@"firstName" ascending:YES withPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)
没有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];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10786 次 |
最近记录: |