1

在我第一次尝试在获取请求中使用 NSExpression 时,我得到的结果与我使用常规获取请求时得到的结果一致。

MO“Subject”与 MO“Book”有一对多的关系,相反的关系是一对一。

这是我正在使用的 NSExpression fetchRequest:

Project_AppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@“Book”
                                                     inManagedObjectContext:context];
Subject *subjectToDelete = [self.arrayOfSubjects objectAtIndex:indexSelected];    
NSPredicate *pred = [NSPredicate predicateWithFormat:@"subject == %@", subjectToDelete];
NSExpression *expn = [NSExpression expressionForFunction:@"count:" 
                                                     arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"idPerm"]]];
NSExpressionDescription *expnDesc = [[NSExpressionDescription alloc] init];
[expnDesc setExpression:expn];
[expnDesc setName:@“countMatchingBooks”];
[expnDesc setExpressionResultType:NSInteger64AttributeType];
NSArray *properties = [NSArray arrayWithObject:expnDesc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription]; 
[request setPredicate:pred];
[request setPropertiesToFetch:properties];
[request setResultType:NSDictionaryResultType];
NSError *error = nil; 
NSArray *results = [context executeFetchRequest:request error:&error];
if (error) {
    // error handling here
}
[request release];
[expnDesc release];

// Retrieve the count from the results array.
NSNumber *numBooksAssignedSubjectToDelete = [[results objectAtIndex:0] valueForKey:@“countMatchingBooks”];
uint64_t uloloBooksAssignedSubjectToDelete = [numBooksAssignedSubjectToDelete unsignedLongLongValue];

(这个想法是向用户提供一个确认面板,告知他们如果他们选择删除所选主题,将通过级联规则删除多少本书 - 此时不会出错。)

这是我用作测试的简单 fetchRequest:

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@“Book”
                                                     inManagedObjectContext:contextMain];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription]; 
NSError *error = nil; 
NSArray *booksAll = [contex executeFetchRequest:request error:&error];
[request release];
// Loop through the “booksAll” array and count those whose subject matches the one assigned as “subjectToDelete”

发生的情况是,如果 NSExpression fetchRequest 返回计数为 n,则简单的 fetchRequest 返回计数为 n + 1。

考虑到 fetchRequests 本身可能会以某种方式改变数据,我尝试以不同的顺序运行它们,但结果相同。

也许使用表达式的请求会跳过尚未保存的 MO?不会。我运行了一个测试,创建了一堆新的“Book” MO,以查看表达式请求和常规请求之间的差距是否会扩大。它仍然是一个关闭。

知道我做错了什么吗?

4

1 回答 1

2

使用 NSExpressionDescription 的 NSFetchRequests 不包括未保存的对象。NSFetchRequest 有一个方法 -setIncludePendingChanges:,当结果类型为 NSDictionaryResultType 时不接受 YES。这意味着您不能使用 NSExpressionDescription 来获取未保存的对象。

于 2011-02-24T08:42:00.557 回答