Restkit to-many relationship append to set instead of setting a new set

半城伤御伤魂 提交于 2019-12-07 06:00:56

问题


I have a iOS Restkit related question. I have a parent-child relationship data coming from a remote server and map those object to a NSManagedObject object with Restkit. The problem that I am currently having is every request to the server always wipe out the "child" relationship and replace it with the new data coming from the server. Is there a way to avoid those and append the new child instead?

For example: I have a classic Category --> Products relationship.

{"categories": [
    {
        "cat_id": "1",
        "cat_title": "category 1",
        "cat_tag": 1,
        "product": [
            {
                "prod_id": "1",
                "prod_name": "product 1",
                "prod_tag": 1
            },
            {
                "prod_id": "2",
                "prod_name": "product 2",
                "prod_tag": 1
            }
        ]
    }
] }

And that works fine and everything is saved properly with the relationship on the CoreData. But if I make another request to the server and have a new response:

{"categories": [
    {
        "cat_id": "1",
        "cat_title": "category 1",
        "cat_tag": 1,
        "product": [
            {
                "prod_id": "3",
                "prod_name": "product 3",
                "prod_tag": 1
            },
            {
                "prod_id": "4",
                "prod_name": "product 4",
                "prod_tag": 1
            }
        ]
    }
] }

I will have product 3 and product 4 replace product 1 and product 2 on the database. I am sure I setup all the relationship and primary key correctly. (Both cat_id and prod_id are set as a primary key).

Having investigated through the RestKit's internal framework, I noticed that around line 576 in the RKObjectMappingOperation class, there is

RKLogTrace(@"Mapped NSSet relationship object from keyPath '%@' to
           '%@'. Value: %@", relationshipMapping.sourceKeyPath,
           relationshipMapping.destinationKeyPath, destinationObject);

NSMutableSet *destinationSet = [self.destinationObject
                         mutableSetValueForKey:relationshipMapping.destinationKeyPath];
[destinationSet setSet:destinationObject];

So I guess that is easy to just change

[destinationSet setSet:destinationObject];

to

[destinationSet addObjectsFromArray:[destinationObject allObjects]]

But I was wondering whether there is a better way to do it?

Cheers,


回答1:


Thanks for the support from Reskit. It is now supported by RKRelationshipMapping.(https://github.com/RestKit/RestKit/issues/989)

Just set assignmentPolicy value of RKRelationshipMapping instance to RKUnionAssignmentPolicy



来源:https://stackoverflow.com/questions/13229767/restkit-to-many-relationship-append-to-set-instead-of-setting-a-new-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!