如何使用 MagicalRecord 过滤和获取记录?
How to filter & fetch records with MagicalRecord?
我有两个这样的类,
@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
但它崩溃并显示以下消息:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format
string "@max.@count.songs"'
我的谓词字符串无效吗?如果是的话,实现这个的正确方法是什么。
根据 this post,您不能在提取时按计数排序。您需要获取所有项目,而不是对它们进行排序和 trim:
NSArray* array = [Album MR_findAll];
array = [array sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"songs.@count" ascending:NO] ] ];
array = [array subarrayWithRange:NSMakeRange(0, MIN( array.count, 5) )];
我有两个这样的类,
@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
但它崩溃并显示以下消息:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "@max.@count.songs"'
我的谓词字符串无效吗?如果是的话,实现这个的正确方法是什么。
根据 this post,您不能在提取时按计数排序。您需要获取所有项目,而不是对它们进行排序和 trim:
NSArray* array = [Album MR_findAll];
array = [array sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"songs.@count" ascending:NO] ] ];
array = [array subarrayWithRange:NSMakeRange(0, MIN( array.count, 5) )];