【问题标题】:Sorting a NSSet of NSManagedObjects by attribute按属性对 NSManagedObjects 的 NSSet 进行排序
【发布时间】:2011-05-26 19:36:36
【问题描述】:

给定一个NSSet,其中包含的对象是NSManagedObject 的子类和一个名为name 的字符串属性,我如何按名称对集合进行排序?这是我会使用NSPredicate 的地方吗?

谢谢!

【问题讨论】:

  • 如果我错了请纠正我,但我相信NSSet 是无序的,这意味着包含的元素没有特定的顺序(从概念上讲),这意味着无法对NSSet 进行排序.你可以把对象放在一个NSArray中,它是有序的,可以排序的。
  • 听起来这就是 OP 的要求...

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


【解决方案1】:

不,但你会使用NSSortDescriptor

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

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

【讨论】:

  • 谢谢!是否需要释放这些以进行内存管理?
  • @Bill sorted 数组是自动释放的,所以没有。
  • 如果我通过 NSSet(array: )) 从排序的 NSArray 创建 NSSet,它会保持顺序吗?
【解决方案2】:

通过提到 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];

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多