RestKit and saving to CoreData as NSManagedObject

后端 未结 2 2027
-上瘾入骨i
-上瘾入骨i 2020-12-08 08:54

I\'m using RestKit and i want to parse and save elements to core data. I have two json files:

First (Category):

[
   {
     \"cat_id\": 3371,
     \"         


        
2条回答
  •  被撕碎了的回忆
    2020-12-08 09:33

    So you've created the mapping for each NSManagedObject (and they work), but now you want to establish a relationship between "Category" and "Elements".

    The problem is that there isn't an information for the mapping of Elements in which Category each element belongs (the unique key is missing). So you need to add the cat_id to the Elements JSON to ensure that this keypath is available.

    // Elements JSON
    [
      {
        "cat_id": "1313",
        "art_id": "1",
        "node": {
          "author": "name"
        },
        "small_url": 0
      },
      ...
    ]
    // Edit keypath in relationship mapping
    [elementsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"cat_id" toKeyPath:@"category" withMapping:categoryMapping]];
    

    In addition you could use the following to methods to track if the mapping works.

    1) -com.apple.CoreData.SQLDebug 1 // Add in "Arguments" Tab > "Arguments Passed On Launch" 
    2) RKLogConfigureByName("RestKit/*", RKLogLevelTrace); // Add to AppDelegate`
    

    Edit

    Mapping

    Did you update the entity Elements in your Data Model and your NSManagedObject with the given value? Seems like you didn't.

    @interface Elements : NSManagedObject
    
    @property (nonatomic, retain) NSNumber * catId;
    @property (nonatomic, retain) NSNumber * artId;
    @property (nonatomic, retain) NSString * author;
    @property (nonatomic, retain) NSString * title;
    @property (nonatomic, retain) NSManagedObject *category;
    
    @end
    

    Routing

    The path your using for your get request won't work because @"/detailaddress/:catId" isn't a valid path. You can on the one hand set the routing of the object manager in general or define a response description.

     // Route for get operation
     [[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute 
          routeWithClass:[Category class] 
          pathPattern:@"/detailaddress/:catId" 
          method:RKRequestMethodGET]];
    
     // Response descriptor taken from the Core Data same application 
     RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:categoryMapping pathPattern:@"/detailaddress/:catId" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];     
     [objectManager addResponseDescriptor:responseDescriptor];
    
     // Use general path for get request
     [[RKObjectManager sharedManager] getObjectsAtPath:@"/detailaddress" ...
    

    But please check if the mapping and data model is set like expected first.

提交回复
热议问题