Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

countForFetchRequest returning 1 for empty table

Tags:

ios

core-data

I am executing a 'countForFetchRequest' and it is always returning 1 more count than the number of records in my table.

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"TESTDATA" inManagedObjectContext:self.managedObjectContext]];

NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:request error:&error];
if(count == NSNotFound) {
    // Handle error
}

return count;

That returns 1 when my table is empty. Returns 4 if my table has 3 rows.

sqlite> select count(*) from ZTESTDATA;
0
sqlite> 

Any ideas on what I am doing wrong?

like image 521
lostintranslation Avatar asked Dec 05 '25 14:12

lostintranslation


1 Answers

Count is always accurate but it counts both what is in memory (not saved yet) and what is on disk.

As others have suggested, do a fetch instead of a count and print out what Core Data finds and you will find your answer.

like image 76
Marcus S. Zarra Avatar answered Dec 09 '25 15:12

Marcus S. Zarra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!