I’m working on my first RestKit app, and I use CoreData for local caching. In it I have a many-to-many relationship between Post <<—>> Category. The relationship is called posts, and categories.
In my Post JSON call I get id’s for the categories like this: {"post": [...] "categories":[1,4] [...], where 1 and 4 is the ids.
I have a custom Post model object that inherits from NSManagedObject, in it I have a property for categories, like this:
@interface Post : NSManagedObject
[...]
@property (nonatomic, retain) NSSet *categories;
[...]
I do the same thing in a custom Category model object.
My mappings currently looks like this:
RKManagedObjectMapping *categoryMapping = [RKManagedObjectMapping mappingForClass:[Category class] inManagedObjectStore:objectManager.objectStore];
categoryMapping.primaryKeyAttribute = @"categoryId";
categoryMapping.rootKeyPath = @"categories";
[categoryMapping mapKeyPath:@"id" toAttribute:@"categoryId"];
[categoryMapping mapKeyPath:@"name" toAttribute:@"name"];
[...]
RKManagedObjectMapping* postMapping = [RKManagedObjectMapping mappingForClass:[Post class] inManagedObjectStore:objectManager.objectStore];
postMapping.primaryKeyAttribute = @"postId";
postMapping.rootKeyPath = @"post";
[postMapping mapKeyPath:@"id" toAttribute:@"postId"];
[...]
[postMapping mapKeyPath:@"created_at" toAttribute:@"createdAt"];
[...]
// Categories many-to-many.
[postMapping mapKeyPath:@"categories" toRelationship:@"categories" withMapping:categoryMapping];
When I run this I get the error: '[<__NSCFNumber 0x6c625e0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key id.'
I would really appreciate if anyone could give me any clues on how to map this relationship.
There error is because your JSON returns each category as a primary key, ie: a NSNumber. But your mapping expects an nested object (which will be transformed into a KVC object). When your map tries to access the property “id” on the KVC object (which is actually a NSNumber), it will crash like this.
I’m not sure if it will work, but you can try something like this:
Normally, you would use the [RKManagedObjectMapping connectRelationship:withObjectForPrimaryKeyAttribute:] method, but I don’t know if this will work on a many-to-many relationship. You may have to modify the source code to do this. The code to look at is inside [RKManagedObjectMappingOperation connectRelationship:].
Otherwise, if possible I would suggest you change your JSON source so the categories array is like this: “categories” : [{“categoryID: 1}, {“categoryID” : 4}]. If the source is not possible to change, you can modify the data manually using the delegate methods or the RKObjectLoader extension I have given below:
.h
.m