我有两个这样的课程,
@class Songs;
@interface Album : NSManagedObject
@property (nonatomic, retain) NSNumber * albumID;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *songs;
@end
@interface Album (CoreDataGeneratedAccessors)
- (void)addSongsObject:(Songs *)value;
- (void)removeSongsObject:(Songs *)value;
- (void)addSongs:(NSSet *)values;
- (void)removeSongs:(NSSet *)values;
@end
@class Album;
@interface Songs : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * length;
@property (nonatomic, retain) Album *owner;
@end
假设我创建了10张专辑,每张专辑都有一些随机(正面)的歌曲数量。现在我想找到&获取拥有最多歌曲数量的前5张专辑。
我如何使用MagicalRecords做到这一点?
目前,我这样做,
NSLog(@"%@",[Album MR_findAllSortedBy:@"albumID" ascending:YES withPredicate:[NSPredicate predicateWithFormat:@"@max.@count.songs"]]);
//NSLog(@"%@",[Album MR_findAllSortedBy:@"albumID" ascending:YES]); //works fine
但它崩溃了以下消息:
***由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'无法解析格式 string" @max。@ count.songs"'
我的谓词字符串无效吗?如果是,那么实现这一目标的正确方法是什么。
答案 0 :(得分:0)
根据this post,您无法按取指数排序。您需要获取所有项目,然后对它们进行排序和修剪:
NSArray* array = [Album MR_findAll];
array = [array sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"songs.@count" ascending:NO] ] ];
array = [array subarrayWithRange:NSMakeRange(0, MIN( array.count, 5) )];