views:

112

answers:

1

Hi,

I'm newbie in coredata and still learning. I have an application which need to fetch number of records which fulfill given criteria.

Assume I have 3 types of Entity, i.e. Entry, Tag and Attachment. Entry has to-many relationship with Tag and Attachment. Tag has to-one relationship with Entry. Attachment has to-one relationship with Entry.

For following code snippets:

NSFetchRequest *req = [[NSFetchRequest alloc] init];
NSEntityDescription entity = [NSEntityDescription entityForName:@"Entry" inManagedContext:ctx];
[req setEntity:entity];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name like 'a*') AND (tags.name like 'test*') OR (attachments.name like 'photo*')"];
[req setPredicate:pred];

NSUInteger count1 = [ctx countForFetchRequest:req error:nil];
NSUInteger count2 = [[ctx executeFetchRequest:req error:nil] count];

Apparently the result returns by the 2 calls above is different. The count1 result is wrong and count2 result is correct. count1 is showing result bigger than it supposed to be.

Anyone has clue why the result are different for above codes?

Thanks, Meiwin

A: 

I tried running your code in my own project. After correcting

NSEntityDescription entity = [NSEntityDescription entityForName:@"Entry" inManagedContext:ctx];

to

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:ctx];

I got the following error: "to-many key not allowed here". Perhaps you could provide some working code?

Elise van Looij