RestKit 0.20: Map relational data from local file - iphone

I'm taking a local JSON file and trying to map it into a relational mapping. It works fine without the relationship, but once I add the relationship, I get an error.
JSON:
https://gist.github.com/4675414
Code:
// Get json from destination
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:contentPath encoding:NSUTF8StringEncoding error:NULL];
NSString* MIMEType = #"application/json";
NSError* parseError;
NSData *data = [myJSON dataUsingEncoding:NSUTF8StringEncoding];
id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:MIMEType error:&parseError];
if (parsedData == nil && parseError) {
NSLog(#"Cannot parse data: %#", parseError);
}
// Setting up objectmapping for issue
RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[Issue class]];
[issueMapping addAttributeMappingsFromDictionary:#{
#"title": #"title",
#"description": #"description",
#"cover_url": #"cover_url",
#"published_at": #"published_at",
#"issue_number": #"issue_number"
}];
//Setting up objectmapping for article
RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping addAttributeMappingsFromDictionary:#{
#"title": #"title",
#"main_text": #"main_text",
#"article_image_url": #"article_image_url"
}];
[issueMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"articles" toKeyPath:#"articles" withMapping:articleMapping]];
Issue *issue = [[Issue alloc] init];
RKMappingOperation* mapper = [[RKMappingOperation alloc] initWithSourceObject:[parsedData objectForKey:#"issue"] destinationObject:issue mapping:issueMapping];
RKManagedObjectMappingOperationDataSource *mappingDS = [RKManagedObjectMappingOperationDataSource new];
mapper.dataSource = mappingDS;
[mapper performMapping:&parseError];
NSLog(#"Parse error: %#", parseError);
NSLog(#"Issue title: %#", issue.title);
Error:
2013-01-30 13:07:42.486 uninkd[13722:907] *** Assertion failure in -[RKManagedObjectMappingOperationDataSource mappingOperation:targetObjectForRepresentation:withMapping:inRelationship:], /Users/holgersindbaek/Projects/Uninkd/Uninkd_IOS/Pods/RestKit/Code/CoreData/RKManagedObjectMappingOperationDataSource.m:232
2013-01-30 13:07:42.487 uninkd[13722:907] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'RKManagedObjectMappingOperationDataSource must be initialized with a managed object context.'
Error if I take away the data source:
2013-01-30 13:27:32.601 uninkd[13754:907] *** Assertion failure in -[RKMappingOperation applyRelationshipMappings], /Users/holgersindbaek/Projects/Uninkd/Uninkd_IOS/Pods/RestKit/Code/ObjectMapping/RKMappingOperation.m:699
2013-01-30 13:27:32.603 uninkd[13754:907] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot perform relationship mapping without a data source'
Hope you can help.

This is because RKManagedObjectMappingOperationDataSource is expecting a managed object context, this is specifically for Core Data. Are you using core data?
Forget everything I previously said and use:
#import "RKObjectMappingOperationDataSource.h"
RKObjectMappingOperationDataSource *mappingDS = [RKObjectMappingOperationDataSource new];
mapper.dataSource = mappingDS;
instead of:
RKManagedObjectMappingOperationDataSource *mappingDS = [RKManagedObjectMappingOperationDataSource new];
mapper.dataSource = mappingDS;
A hint, don't use any classes that say ManagedObject if you're not using CoreData. This is referring to a ManagedObject in a ManagedObjectContext which is unique to CoreData. That being said, core data + restkit is awesome and you should check it out.

Related

JSONKit invalid arguement when try to copy

I am parsing JSON data with JSONKit as NSMutableDictionary.
NSString *str = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *jsonResponse = [self.responseData objectFromJSONData];
NSMutableDictionary *newData = [[NSMutableDictionary alloc] init];
[newData addEntriesFromDictionary:[jsonResponse mutableCopy]];
When i do this i am getting this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableDictionary addEntriesFromDictionary:]: dictionary argument is not an NSDictionary'
I am trying to figure out what is causing this problem. I know that jsonResponse is an object of JKArray from my other experience.
I need help.
Thanks.
Try the following:
id object = [self.responseData objectFromJSONData];
NSLog(#"%#", [object class]);
Most likely your response is an array instead of a dictionary.
If you really want to convert the array into a dictionary, you could do something like this, using a self-defined key:
NSArray *array = [self.responseData objectFromJSONData];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:array forKey:#"posts"];
Though perhaps there are some better options if you could show me the contents of your array.

RestKit mapping error when sending image with RKObjectMapping

Here is the object RestKit mapping:-
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ImageModel class]];
[mapping mapKeyPath:#"Description" toAttribute:#"description"];
[mapping mapKeyPath:#"Photo1" toAttribute:#"photo1"];
[objectManager.mappingProvider addObjectMapping:mapping];
RKObjectMapping* serializeMapping = [mapping inverseMapping];
[objectManager.mappingProvider setSerializationMapping:serializeMapping forClass:[ImageModel class]];
[objectManager.router routeClass:[ImageModel class] toResourcePath:#"/image" forMethod:RKRequestMethodPOST];
[objectManager.mappingProvider setObjectMapping:mapping forResourcePathPattern:#"/image"];
And here is the ImageModel object:-
#property (strong,nonatomic) NSString *description;
#property (strong,nonatomic) UIImage *photo1;
Here are three different ways that i have tried but all with errors:-
Method1.
Simply use the following code to post object.
obj.description = self.descriptionText.text;
obj.photo1 = selectedImage;
[[RKObjectManager sharedManager] postObject:obj delegate:self];
Result:-
The object is posted to the server and the server script returns the same object back. The response is received at the client side but the following mapping related exception occurred.
2012-10-26 20:16:39.015 APP[4548:7407] W restkit.object_mapping:RKObjectMappingOperation.m:244 Failed transformation of value at keyPath 'Photo1'. No strategy for transforming from '__NSCFString' to 'UIImage'
The log does show that the returned object's Photo1 field does have photo data, but what's missed from the mapping is not understandable. Any idea from RestKit gurus will be very helpful!
Method 2 - Call sendObject:toResourcePath:usingBlock
[[RKObjectManager sharedManager] sendObject:self.obj toResourcePath:#"/image" usingBlock:^(RKObjectLoader *loader) {
loader.targetObject = nil;
loader.delegate = self;
loader.method = RKRequestMethodPOST;
if([obj photo1]){
RKObjectMapping* serializationMapping = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[ImageModel class]];
NSError* error = nil;
NSDictionary* dictionary = [[RKObjectSerializer serializerWithObject:obj mapping:serializationMapping] serializedObject:&error];
NSLog(#"%#", dictionary);
RKParams* params = [RKParams paramsWithDictionary:dictionary];
NSData* imageData = UIImagePNGRepresentation([obj photo1]);
[params setData:imageData MIMEType:#"image/png" forParam:#"Photo1"];
loader.params = params;
}
}];
Result:
Following error appears in the log window.
2012-10-26 20:32:15.327 APP[4627:c07] response code: 500
2012-10-26 20:32:22.388 APP[4627:c07] Loaded payload: {"Message":"An error has occurred."}
2012-10-26 20:32:27.878 APP[4627:c07] W restkit.object_mapping:RKObjectMapper.m:87 Adding mapping error: Could not find an object mapping for keyPath: ''
2012-10-26 20:32:27.878 APP[4627:c07] E restkit.network:RKObjectLoader.m:231 Encountered errors during mapping: Could not find an object mapping for keyPath: ''
Method 3
Call postObject:usingBlock
[[RKObjectManager sharedManager] postObject:obj usingBlock:^(RKObjectLoader *loader){
loader.delegate = self;
RKParams* params = [RKParams params];
[params setValue:obj.description forParam:#"Description"];
[params setData:[app convertImageToNSData: [app photo1]] MIMEType:#"image/png" forParam:#"Photo1"];
loader.params = params;
}];
Result:-
Following exceptions appear in the log window.
2012-10-26 20:42:07.735 APP[4670:c07] response code: 500
2012-10-26 20:42:10.726 APP[4670:c07] Loaded payload: {"Message":"An error has occurred."}
2012-10-26 20:42:16.569 APP[4670:c07] W restkit.object_mapping:RKObjectMapper.m:87 Adding mapping error: Could not find an object mapping for keyPath: ''
2012-10-26 20:42:16.570 APP[4670:c07] E restkit.network:RKObjectLoader.m:231 Encountered errors during mapping: Could not find an object mapping for keyPath: ''
2012-10-26 20:42:16.570 APP[4670:c07] E restkit.network:RKObjectLoader.m:360 Encountered an error while attempting to map server side errors from payload: Could not find an object mapping for keyPath: ''
Apparently I am not missing anything in the mapping, but might I am . Can RestKit gurus help me any of these 3 methods to help me able to send an object having an image in one of it's fields to the server.

core data countByEnumeratingWithState:objects:count: error

i have this error when i add to core data new relationship. I read in internets many resources but they can`t help me... Maybe you can...
This is my code then i adding relationship:
std = [NSEntityDescription insertNewObjectForEntityForName:#"Student" inManagedObjectContext:self.context];
std.fio = fio.text;
std.phone = phone.text;
NSError *error;
self.selectedGroups = MSGTVC.selectedGroups;
for(Group *info in self.selectedGroups){
[std addGroupsObject:info];
} if (![self.context save:&error]) {
NSLog(#"Cant Save: %#", [error localizedDescription]); }
in line [std addGroupsObject:info]; is error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Group countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x816a1c0'
This is my code then i assign value to selectedGroups:
NSArray *indexselected = [[NSArray alloc] initWithArray:[self.tableView indexPathsForSelectedRows
__OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_5_0)]];
for (NSIndexPath *into in indexselected)
{
self.selectedGroups = [self.group objectAtIndex:into.row];
}
I'll be happy if you help solve this problem, thanks in advance.

Getting error when trying to set value/key pairs with SBJsonWriter

Getting the following error when trying to set value/key pairs:
2011-06-21 16:21:16.727 agent[94408:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<SBJsonWriter 0xab31230> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key key.'
Here is the code:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
[writer setValue:#"val" forKey:#"key"];
NSString *json = [writer JSONRepresentation];
NSLog([NSString stringWithFormat:#"json: #%", json]);
that is using the key-value coding from the (NSObject) category,
to use the dictionary interface:
import JSON.h then:
NSMutableDictionary * dict = [NSMutableDictionary new];
[dict setValue:#"val" forKey:#"key"];
NSLog(#"json: %#", [dict JSONRepresentation]);
p.s. NSLog accepts a format, so you don't need to make a string from a format to pass to it.

-[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x6a3fc60'

I was preparing for a customCellView in a tableView. According to me, everything was perfect in .xib and methods. I am getting an exception in configuring the cell.
int listIndex = [indexPath indexAtPosition:[indexPath length] - 1];
NSLog(#"outside");
cell.lblName.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesName"];
cell.lblSize.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesSize"];
cell.lblType.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesType"];
return cell;
The compiler works till the NSLog(#"outside");. But it does not proceeds to the next line. I am terminated by the error
2010-11-15 20:32:28.623 iDataTraveller[5346:207] outside
2010-11-15 20:32:28.625 iDataTraveller[5346:207] -[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x5f19cf0
2010-11-15 20:32:28.627 iDataTraveller[5346:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x5f19cf0'
Please help me to proceed.. Thank you in advance..
Wherever you created directoryContent, you stored the wrong object in it.
NSPathStore2 is an object that will be created if you use something like stringByAppendingPathComponent: on a NSString.
I guess you just stored the filename in the array but wanted to store a NSDictionary created from NSFileManagers attributesOfItemAtPath:error:
Check that part were you add objects to directoryContent again.
This is my code. Have a look at this. Let me know what i am lagging.
- (void)listFiles {
NSFileManager *fm =[NSFileManager defaultManager];
NSError *error = nil;
NSString *parentDirectory = #"/Users/akilan/Documents";
NSArray *paths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
NSMutableArray *array = [[NSMutableArray alloc] init];
self.directoryContent = array;
[array release];
for (NSString *path in paths){
filesName = [[path lastPathComponent] stringByDeletingPathExtension];
filesPath = [parentDirectory stringByAppendingPathComponent:path];
filesDirectory = [NSMutableDictionary dictionaryWithDictionary:[[NSFileManager defaultManager] attributesOfItemAtPath:filesPath error:nil]];
filesSize = [filesDirectory objectForKey:NSFileSize];
filesType = [path pathExtension];
createdDate = [filesDirectory objectForKey:NSFileCreationDate];
modifiedDate = [filesDirectory objectForKey:NSFileModificationDate];
filesDirectory = [NSDictionary dictionaryWithObjectsAndKeys:filesPath,#"filesPath",
filesName,#"filesName",filesSize, #"filesSize", filesType, #"filesType",
createdDate,#"createdDate", modifiedDate,#"modifiedDate", nil];
NSLog(#"%#", filesDirectory);
}
}
Thanks..
You have not retained directoryContent.
Can you show the code where directoryContent is created?
You can tell this because your error message says NSPathStore2 when it should be trying to call objectforKey on NSDictionary - this means that the memory where your dictionary was is not being used by something else :)