【问题标题】:(Core Data )Fetch an specific entity with a max property(核心数据)获取具有 max 属性的特定实体
【发布时间】:2011-03-03 00:00:43
【问题描述】:

我有一个实体,它与另一个实体有 toMany 关系。在第二个中,我有一个名为“versionNumber”的属性。我在实体类型 A 上有一个对象,我想获取具有最大(最大)版本号的相关实体 B。

我有以下内容,但它返回的结果是通过实体 B 上的所有记录获得的,而不是通过与类型 A 的对象相关的特定实体获得的结果。

   NSInteger vNumber = 0;

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:DPA_VERSION_KEY inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];

// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:VERSION_NUMBER_KEY];
NSExpression *maxNumberExpression = [NSExpression expressionForFunction:@"max:"
                                                              arguments:[NSArray arrayWithObject:keyPathExpression]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxNumber"];
[expressionDescription setExpression:maxNumberExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];






[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch.
NSError *error = nil;
NSArray *objects = [[self managedObjectContext] executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}
else {
    if ([objects count] > 0) {
        vNumber = [[[objects objectAtIndex:0] valueForKey:@"maxNumber"] integerValue] +1;
    }
}

[expressionDescription release];
[request release];

return vNumber;

我有一个想法,但我无法实现它。我必须询问 SELF 哪个是我的对象 A 来获取它与版本(实体 B)的关系。 感谢您的帮助。

G.

【问题讨论】:

  • 嗯,当然,没问题。

标签: core-data


【解决方案1】:

设置谓词,将请求限制为仅与 A 有关系的 B 对象。

[request setPredicate:[NSPredicate predicateWithFormat:@"myA == %@", myA];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多