radven
radven

Reputation: 2336

Bizarre Core Data behavior when fetching unsaved data

I have a Core Data importer that loops through data, and ignores duplicate records during the import process.

But I have discovered that my NSFetchRequest is not matching against recently stored records that have not been saved. And I am seeing seemingly identical queries delivering different and unexpected results.

For example, in my testing, I discovered that this query matches and returns results:

fetchTest.predicate = [NSPredicate predicateWithFormat:@"%K = 3882", @"intEmployee_id"];

But this seemingly identical one does not:

fetchTest.predicate = [NSPredicate predicateWithFormat:@"%K = %@", @"intEmployee_id", @"3882"];

But - they both match identically after the context is saved to the persistent store.

Apple's documentation says that fetches should work against pending changes by default, and indeed I have conformed that [fetchTest includesPendingChanges] = YES.

Any ideas what on earth is going on here? How is it possible that those two fetches return different results?

Upvotes: 0

Views: 163

Answers (2)

lnafziger
lnafziger

Reputation: 25740

These actually don't evaluate to the same value.

[NSPredicate predicateWithFormat:@"%K = 3882", @"intEmployee_id"]

evaluates to intEmployee_id = 3882 while

[NSPredicate predicateWithFormat:@"%K = %@", @"intEmployee_id", @"3882"]

evaluates to intEmployee_id = "3882"

Try using a number instead of a string for the id.

Upvotes: 1

Mundi
Mundi

Reputation: 80265

Maybe the employee id is not a string but a number? Then the predicate should be:

[NSPredicate predicateWithFormat:@"%K = %@", @"intEmployee_id",
                                             [NSNumber numberWithInt:3882]];

This would imply that the erratic behavior comes from mixing up the types. It still works somehow, even if erratically, because in the SQLite docs it says that SQLite actually does not really distinguish by type when storing the data physically.

See Distinctive Features of SQLite from the SQLite web site, under the heading Manifest Typing.

Upvotes: 1

Related Questions