A7madev
A7madev

Reputation: 728

Restkit Add custom values when mapping

Restkit mapping and inserting data works fine, but I need to add custom values to the database (not from JSON)

RKEntityMapping *entityMapping = [RKEntityMapping mappingForEntityForName:entityName inManagedObjectStore:managedObjectStore];

[entityMapping addAttributeMappingsFromDictionary:dict];

if (uniqKey != nil) {
    entityMapping.identificationAttributes = @[ uniqKey ];
}

// Set MIME Type to JSON
manager.requestSerializationMIMEType = RKMIMETypeJSON;

// register mappings with the provider using a response descriptor
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:entityMapping
                                             method:RKRequestMethodPOST
                                        pathPattern:path
                                            keyPath:rootKeyPath
                                        statusCodes:[NSIndexSet indexSetWithIndex:200]];

[manager addResponseDescriptor:responseDescriptor];

[manager postObject:nil path:path parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if (mappingResult.array.count != 0) {
    NSDictionary *data = mappingResult.array[0];       
    NSLog(@"data: %@", data);      
}else{
    NSLog(@"Unable to fetch data from: %@", path);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Error response': %@", error);
}];

Other than NSPredict and filtering the data, is is possible to insert values (like string) manually while mapping?

Upvotes: 4

Views: 711

Answers (2)

A7madev
A7madev

Reputation: 728

Solved the issue using

[[mappingResult set] setValue:value forKey:key]; 

in manager on success block.

Upvotes: 2

Wain
Wain

Reputation: 119031

You can modify the objects from the mapping result in the completion block, but then you need to explicitly save the context and other observers of the context will have received a save notification. This is the super simple approach.

Alternatively you could override willSave or use NSManagedObjectContextWillSaveNotification (the latter being the better option) to trigger your custom logic. Your changes would then be made inline with the RestKit changes and would be automatically saved.

Upvotes: 6

Related Questions