Search code examples
cocoa-touchcore-datansfetchrequest

Core data: renaming a property while fetching


I have two entities with below relationship:

Contact <--> ContactMeta

Here, Contact has one of the relationships as 'contactMeta' and ContactMeta has one of the attributes as 'operation'.

I am firing a fetchRequest on Contact entity. The result type is NSDictionaryResultType.

So I am getting an array of dictionaries, which I am serializing using NSJSONSerialization and sending as JSON request to server.

Now, I am adding "contactMeta.operation" to propertiesToFetch list, so one of the keys in dictionary is "contactMeta.operation".

Problem is- I need to send "operation" as key, in place of "contactMeta.operation", in JSON request.

I have one option- to iterate through each dictionary in the list, adding a key- "operation" with value as value for key "contactMeta.operation", and then removing the key-value for "contactMeta.operation".

But I am not satisfied with this approach and was thinking that in sqlite we can have a query like this:

Select first_name, last_name, contactmeta as operation from contact;

Can we do similar stuff in core data or is there any smart and better way to implement what I am trying to do?

Please suggest.


Solution

  • Your hunch was right, there is another way. NSExpressionDescription is what you are looking for.

        NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Contact"];
        [request setResultType:NSDictionaryResultType];
        NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"contactmeta"];
        NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
        [expressionDescription setName:@"operation"];
        [expressionDescription setExpression:keyPathExpression];
        [expressionDescription setExpressionResultType:NSUndefinedAttributeType];
        [request setPropertiesToFetch:@[@"first_name",@"last_name",expressionDescription]];
        NSError* error = nil;
        NSArray* rez = [context executeFetchRequest:request error:&error];