【发布时间】:2015-02-25 11:05:56
【问题描述】:
我的核心数据模型中有两个类,它们是一对多的关系。
我们以班级专辑>班级歌曲为例进行说明。现在我想从Album 中获取(顶部)五个专辑,其中有Songs 的最大数量。
Class Album
{
albumID (Integer)
name (String)
songs (class B)
}
Class Songs
{
name (String)
length (Integer)
}
@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
这就是我正在尝试的,
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Albums" inManagedObjectContext:[self context]]];
fetchRequest.fetchOffset = 0;
fetchRequest.fetchLimit = 5;
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"albumID" ascending:YES]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF @max.@count.songs"];
NSError *error = nil;
NSArray *albums = [[self context] executeFetchRequest:fetchRequest error:&error];
如果我不通过谓词,它可以正常工作。但问题在于谓词。它使应用程序崩溃并显示以下消息:
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法解析格式 字符串 "SELF @max.@count.songs"'
更新:我正在尝试与NSExpression 相同但无法同时执行max: 和count: 函数?以下是我尝试过的,
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Albums" inManagedObjectContext:[self context]]];
fetchRequest.fetchOffset = 0;
fetchRequest.fetchLimit = 5;
NSError *error = nil;
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"songs"];
NSExpression *countExpression = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:keyPathExpression]];
//NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *maxCountExpressionDescription = [[NSExpressionDescription alloc] init];
[maxCountExpressionDescription setName:@"squishes"];
[maxCountExpressionDescription setExpression:countExpression];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:maxCountExpressionDescription]];
[fetchRequest setResultType:NSDictionaryResultType];
NSArray *albums = [[self context] executeFetchRequest:fetchRequest error:&error];
我想,我需要这样查询,
从专辑中选择专辑名称,最大值(计数(专辑.歌曲));
如何在NSFetchRequest中创建这样的查询,NSExpression或NSPredicate可以吗?
【问题讨论】:
-
在
Class Album...songs属性中,它是一个什么样的类...?你能复制完整的头文件(以及生成的方法)吗? -
@geo,请查看更新后的问题。
标签: ios core-data nspredicate aggregation nsfetchrequest