我有一个名为Workshop的核心数据对象。它与Student对象有很多关系。
如何从Workshop对象获得NSArray
学生姓氏(姓氏为Student NSString
属性)?最好按字母顺序排列?
答案 0 :(得分:2)
警告:未经测试的代码传入
假设您的Workshop和Student实体都有一个“name”属性,并且您的学生实体有一个名为“Workshop”的关系,这就是您获取对象的方式:
- (NSArray*) getStudentsForWorkshop:(NSString*) workshopName {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student"
inManagedObjectContext:managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Workshop.name LIKE %@", workshopName];
[fetchRequest setPredicate:predicate];
[fetchRequest setEntity:entity];
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:nil]];
NSArray *sortedArray = [NSArray arrayWithArray: [result sortedArrayUsingSelector:@selector(compareStudent:)]];
return sortedArray;
}
对于排序,你会像{I}一样实现compareStudent
:
- (NSComparisonResult)compareStudent:(NSManagedObject*)otherObject {
return [self.name compare:otherObject];
}