Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestKit many-to-many mapping, how to?

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.

like image 586
Anders Avatar asked Nov 04 '22 21:11

Anders


1 Answers

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:

RKManagedObjectMapping* categoryMapping = //something
categoryMapping.primaryKeyAttribute = @"categoryId";
[categoryMapping mapKeyPath: @"" toAttribute: @"categoryId"];

[..]

[postMapping mapKeyPath: @"categories" toRelationship: @"categories" withMapping: categoryMapping]; 

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

typedef void(^RKObjectLoaderWillMapDataBlock)(id* mappableData);

@interface RKObjectLoader (Extended)

@property (nonatomic, copy) RKObjectLoaderWillMapDataBlock onWillMapData;

@end

.m

#import "RKObjectLoader+Extended.h"

#import <objc/runtime.h>

NSString* kOnWillMapDataKey = @"onWillMapData";

@implementation RKObjectLoader (Extended)

- (RKObjectLoaderWillMapDataBlock) onWillMapData {
    return objc_getAssociatedObject(self, &kOnWillMapDataKey);
}

- (void) setOnWillMapData:(RKObjectLoaderWillMapDataBlock) block {
    objc_setAssociatedObject(self, &kOnWillMapDataKey, block, OBJC_ASSOCIATION_COPY);
}

- (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvider*)mappingProvider toObject:(id)targetObject inContext:(RKObjectMappingProviderContext)context error:(NSError**)error {
    id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:self.response.MIMEType];
    NSAssert1(parser, @"Cannot perform object load without a parser for MIME Type '%@'", self.response.MIMEType);

    // Check that there is actually content in the response body for mapping. It is possible to get back a 200 response
    // with the appropriate MIME Type with no content (such as for a successful PUT or DELETE). Make sure we don't generate an error
    // in these cases
    id bodyAsString = [self.response bodyAsString];
    RKLogTrace(@"bodyAsString: %@", bodyAsString);
    if (bodyAsString == nil || [[bodyAsString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        RKLogDebug(@"Mapping attempted on empty response body...");
        if (self.targetObject) {
            return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionaryWithObject:self.targetObject forKey:@""]];
        }

        return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]];
    }

    id parsedData = [parser objectFromString:bodyAsString error:error];
    if (parsedData == nil && error) {
        return nil;
    }

    // Allow the delegate to manipulate the data
    if ([self.delegate respondsToSelector:@selector(objectLoader:willMapData:)]) {
        parsedData = AH_AUTORELEASE([parsedData mutableCopy]);
        [(NSObject<RKObjectLoaderDelegate>*)self.delegate objectLoader:self willMapData:&parsedData];
    }

    if( self.onWillMapData ) {
        parsedData = AH_AUTORELEASE([parsedData mutableCopy]);
        self.onWillMapData(&parsedData);
    }

    RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
    mapper.targetObject = targetObject;
    mapper.delegate = (id<RKObjectMapperDelegate>)self;
    mapper.context = context;
    RKObjectMappingResult* result = [mapper performMapping];

    // Log any mapping errors
    if (mapper.errorCount > 0) {
        RKLogError(@"Encountered errors during mapping: %@", [[mapper.errors valueForKey:@"localizedDescription"] componentsJoinedByString:@", "]);
    }

    // The object mapper will return a nil result if mapping failed
    if (nil == result) {
        // TODO: Construct a composite error that wraps up all the other errors. Should probably make it performMapping:&error when we have this?
        if (error) *error = [mapper.errors lastObject];
        return nil;
    }

    return result;
}

@end
like image 174
Paul de Lange Avatar answered Nov 09 '22 14:11

Paul de Lange