我第一次使用RestKit,我遇到了将对象保存到数据库时遇到的问题,或者他们的值没有被调整。
我有一个看起来像这样的JSON请求:
{"categories":{"id":1 ...
我像这样设置了类别的映射:
RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURLString:@"[base-url]"];
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"App.sqlite"];
objectManager.objectStore = objectStore;
objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES;
RKManagedObjectMapping *categoryMapping = [RKManagedObjectMapping mappingForClass:[Category class] inManagedObjectStore:objectManager.objectStore];
[objectManager.mappingProvider setObjectMapping:categoryMapping forResourcePathPattern:@"[path-to-json].json"];
[[RKObjectManager sharedManager].mappingProvider setMapping:categoryMapping forKeyPath:@"categories"];
// Maps keys between the database and costom model object.
categoryMapping.primaryKeyAttribute = @"categoryId";
[categoryMapping mapKeyPath:@"categories.id" toAttribute:@"categoryId"];
[categoryMapping mapKeyPath:@"categories.name" toAttribute:@"name"];
[...]
我的类别的自定义模型对象如下所示:
@interface Category : NSManagedObject
@property (nonatomic, retain) NSNumber *categoryId;
@property (nonatomic, retain) NSString *name;
[...]
@implementation Category
@dynamic categoryId;
@dynamic name;
[...]
我加载这样的对象(就像Twitter示例一样):
// Loads from the database
- (void)loadObjectsFromDataStore {
NSFetchRequest *request = [Category fetchRequest];
_categories = [Category objectsWithFetchRequest:request];
}
- (void)loadCategories {
RKObjectManager *objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:@"[path-to-json].json" delegate:self];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// The array is always empty.
NSLog(@"Objects: %@", objects);
[[NSUserDefaults standardUserDefaults] synchronize];
[self loadObjectsFromDataStore];
}
正如我所说,当我从模拟器检查本地数据库时,它会被插入但值为NULL且category_id始终为0.
关于如何解决这个问题的任何想法?非常感谢!
答案 0 :(得分:1)
尝试此映射:
RKManagedObjectMapping* categoryMapping = [RKManagedObjectMapping mappingForClass: [Category class]];
categoryMapping.primaryKeyAttribute = @"categoryId";
categoryMapping.rootKeyPath = @"categories";
[categoryMapping mapKeyPathsToAttributes: @"id", @"categoryId", @"name", @"name", nil];
和
[[RKObjectManager sharedManager].mappingProvider setMapping:categoryMapping forKeyPath:@""];
它说,当你检测到“类别”时使用这个地图,并用“categoryId”索引核心数据对象。
OR
RKManagedObjectMapping* categoryMapping = [RKManagedObjectMapping mappingForClass: [Category class]];
categoryMapping.primaryKeyAttribute = @"categoryId";
[categoryMapping mapKeyPathsToAttributes: @"id", @"categoryId", @"name", @"name", nil];
和
[[RKObjectManager sharedManager].mappingProvider setMapping:categoryMapping forKeyPath:@"categories"];