RestKit/RestKit — Issue #478: -findOrCreateInstanceOfEntity Cache Problem
Author: scraton
Created: 2011-12-18 02:24:28+00:00
State: open

The `- (NSManagedObject*)findOrCreateInstanceOfEntity:withPrimaryKeyAttribute:andValue:` method of the `RKManagedObjectStore` has an issue with it's entity cache. Let's say you have two objects in your store. One has a primary key with an `NSNumber` of 1. The other has a primary key value that is nil.

What will happen is the cache is generated, but it fails to coerce the primary keys into strings. So when it goes to look up an existing object, it will fail since it can't find an object with `@"1"` as a key, but rather `[NSNumber numberWithInt:1]`.

Here's the problem area:

```objc
BOOL coerceToString = [[[objects lastObject] valueForKey:primaryKeyAttribute] respondsToSelector:@selector(stringValue)];
```

Again, if the last object's primary key is null, this will always be false. I think this should be done on a per-object basis, right? Something like this:

```objc
for (id theObject in objects) {
id attributeValue = [theObject valueForKey:primaryKeyAttribute];
// Coerce to a string if possible
attributeValue = [[theObject valueForKey:primaryKeyAttribute] respondsToSelector:@selector(stringValue)] ? [attributeValue stringValue] : attributeValue;
if (attributeValue) {
[dictionary setObject:theObject forKey:attributeValue];
}
}
```

This has fixed my issues so far, but I'm not sure how reliable this fix will be.