RestKit将托管对象与非托管对象相结合

时间:2014-04-30 17:03:42

标签: core-data restkit

我试图在我的请求中使用NSManagedObject作为响应类,但是我的关系也需要饱和,我不想管理,因为它们的更改频率更高。我试图使用简单的NSObject以及与NSManagedObject的短暂关系,但这两种方法最终都是空关系(瞬态或NSObject不要饱和了。

这是我想要从请求中解除并存储在SQLite中的对象:

@interface Car : NSManagedObject

@property (nonatomic, retain) NSString *brand
@property (nonatomic, retain) MLocation *location //don't want persisted

@end

以下是想要保持但饱和的对象:

//I have tried this with NSObject and NSManagedObject
@interface MLocation : NSObject

@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) double longitude;

@end

这是响应描述符:

[manager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:self.buildCarMapping
                                                                            method:RKRequestMethodGET
                                                                       pathPattern:@"/v1/cars/near/:latitude/:longitude"
                                                                           keyPath:nil
                                                                       statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)] ];

这是对象映射:

- (RKObjectMapping *)buildCarMapping {
    RKEntityMapping *carMapping = [RKEntityMapping mappingForEntityForName:@"Car" inManagedObjectStore:self.managedObjectStore];
    [carMapping addAttributeMappingsFromDictionary:@{
            @"brand" : @"brand"
    }];

    [carMapping addRelationshipMappingWithSourceKeyPath:@"location" mapping:self.buildLocationMapping];
    return carMapping;
}

//I have tried this with NSObject and a transient NSManagedObject relationship
- (RKObjectMapping *)buildLocationMapping {
    RKObjectMapping *locationMapping = [RKObjectMapping mappingForClass:[MLocation class]];
    [locationMapping addAttributeMappingsFromDictionary:@{
            @"longitude": @"longitude",
            @"latitude": @"latitude"
    }];
    return locationMapping;
}

以下是一个示例回复:

{
  "brand": "Chevy",
  "location": {  //This is ignored by RestKit using my mappings
    "latitude": 42.8,
    "longitude": -98.6
  }
}

1 个答案:

答案 0 :(得分:0)

我认为没有办法实现这一点,因为托管对象是在后台线程上创建的,而将它们还给你的唯一方法就是销毁这些实例(使用你的临时数据)并从主线程上的持久数据生成相应的实例。

如果您在当前线程上自己创建并执行映射操作,它可能会起作用,但是您需要管理/处理问题的其他一些要求。

我会考虑使用2个响应描述符。第一个,就像您一样,将处理Core Data相关内容到持久性存储中。第二个用于在适当的实例层次结构中创建普通(临时)对象,该对象包含唯一标识符(根据需要),以便您可以在需要时获取关联的托管对象。你不会有直接的关系,但你会得到你需要的所有信息。