2

我有一个具有某些属性的实体。我的标签已经填充(SQLite 表)在一个属性中(我将调用 Attribute1)我有一个布尔值,在使用我的应用程序期间会发生变化。

如何返回我的 Attribute1 值为 YES 的实体的计数?

我已经阅读了“核心数据教程”和“谓词编程指南”,但我不明白如何继续..

    NSPredicate *predicate= [NSPredicate predicateWithFormat:@"Attribute1 == %@",[NSNumber numberWithBool:YES]];

这个我试过了,然后呢?好像不行。。

4

1 回答 1

3

最好的办法是使用 countForFetchRequest 方法。设置您的谓词和获取请求,但不是执行实际的获取,而是执行 countForFetchRequest,如下所示:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];

NSPredicate *predicate = 
    [NSPredicate predicateWithFormat:@"Attribute1 == %@",
        [NSNumber numberWithBool:YES]];

[request setPredicate:predicate];

NSUInteger count = [myManagedObjectContext countForFetchRequest:request error:nil];

您可以在 Apple API 文档中找到更多信息:

countForFetchRequest:error:返回给定的获取请求如果已传递给 executeFetchRequest:error: 将返回的对象数。

  • (NSUInteger)countForFetchRequest:(NSFetchRequest )request error:(NSError * )error 参数 request 指定获取搜索条件的获取请求。error 如果执行获取时出现问题,返回时包含描述问题的 NSError 实例。返回值 如果给定的获取请求已被传递给 executeFetchRequest:error: 或 NSNotFound 如果发生错误,则返回值将返回的对象数。

可用性 适用于 iOS 3.0 及更高版本。在 NSManagedObjectContext.h 中声明

于 2011-09-26T15:19:33.920 回答