Agustin
Agustin

Reputation: 433

How to deal with an empty object {} in RestKit

The response I sometimes get from the server is a JSON representing an empty object like this {}

I've read this question/answer over here already, which states I should implement the willMapData delegate function and point the *mappableData somewhere else. The thing is I can't figure out what should I assign to *mappableData so that my app won't crash.

I've tried this

- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableData
{
    id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON]; 
    *mappableData = [parser objectFromString:@"{\"unknownObject\":\"\"}" error:nil];
}

But nevertheless my app crashes with a rather pissing

    'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary   initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]

Can you help me out?

UPDATE Turning on RKDebug messages gives me this in the console:

Performing object mapping sourceObject: {
    }
and targetObject: (null)

then the code reaches RKObjectMapper.m:

if (mappableData) {
        id mappingResult = [self performMappingForObject:mappableData atKeyPath:@"" usingMapping:mappingsForContext];
        foundMappable = YES;
        results = [NSDictionary dictionaryWithObject:mappingResult forKey:@""];
    }

but mappingResult over there comes back nil... so the app crashes when it tries to create an NSDictionary with a nil object.

Upvotes: 1

Views: 916

Answers (1)

Moshe
Moshe

Reputation: 58087

Break up the assignment into two lines.

SomeDataType *object =  [parser objectFromString:@"{\"unknownObject\":\"\"}" error:nil];

if(object){
  *mappableData = object;
}else{
  // You've got nil, do something with it
}

Now you can check for nil values and take the appropriate action. What that action is depends on the context of the crash.

Upvotes: 1

Related Questions