【问题标题】:RestKit Combine Managed Objects with Non-Managed ObjectsRestKit 将托管对象与非托管对象结合起来
【发布时间】:2014-04-30 17:03:42
【问题描述】:

我正在尝试在我的请求中使用NSManagedObject 作为响应类,但我也有一些我需要饱和的关系,我不想对其进行管理,因为它们的变化要频繁得多。我尝试使用简单的NSObject 以及与NSManagedObject 的瞬态关系,但任何一种方法都以空关系结束(瞬态或NSObjects 不会饱和)。

这是我想要从请求中饱和并存储在 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
  }
}

【问题讨论】:

    标签: core-data restkit


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 2021-07-15
      相关资源
      最近更新 更多