2

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 *predicate= [NSPredicate predicateWithFormat:@"Attribute1 == %@",[NSNumber numberWithBool:YES]];

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

1 Answers1

3

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

Max MacLeod
  • 26,115
  • 13
  • 104
  • 132