开发者

Count entity in Core Data with a specific Value

I have an Entity with some Attribute. I have my tabes already populates(SQLite table) In one Attribute (i'll call Attribute1) i have a bool value, changing during use of my app.

How can i return the count of my Entities with Attribute1 value YES?

I've already read "Core data Tutorial" and "Predicate Programing Guide" but i don't understand how to proceed..

    NSPredicate *pr开发者_如何学Goedicate= [NSPredicate predicateWithFormat:@"Attribute1 == %@",[NSNumber numberWithBool:YES]];

I've tried with this, and then? it seems not working..


The best bet is to use the countForFetchRequest method. Set up your predicate and fetch request, but instead of doing the actual fetch, execute countForFetchRequest as follows:

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

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

[request setPredicate:predicate];

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

You can find more info in the Apple API Docs:

countForFetchRequest:error: Returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:.

  • (NSUInteger)countForFetchRequest:(NSFetchRequest )request error:(NSError *)error Parameters request A fetch request that specifies the search criteria for the fetch. error If there is a problem executing the fetch, upon return contains an instance of NSError that describes the problem. Return Value The number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:, or NSNotFound if an error occurs.

Availability Available in iOS 3.0 and later. Declared In NSManagedObjectContext.h

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜