Restkit在映射时添加自定义值

4
Restkit的映射和插入数据很好用,但是我需要将自定义数值添加到数据库中(不是从JSON中获取)。
RKEntityMapping *entityMapping = [RKEntityMapping mappingForEntityForName:entityName inManagedObjectStore:managedObjectStore];

[entityMapping addAttributeMappingsFromDictionary:dict];

if (uniqKey != nil) {
    entityMapping.identificationAttributes = @[ uniqKey ];
}

// Set MIME Type to JSON
manager.requestSerializationMIMEType = RKMIMETypeJSON;

// register mappings with the provider using a response descriptor
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:entityMapping
                                             method:RKRequestMethodPOST
                                        pathPattern:path
                                            keyPath:rootKeyPath
                                        statusCodes:[NSIndexSet indexSetWithIndex:200]];

[manager addResponseDescriptor:responseDescriptor];

[manager postObject:nil path:path parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if (mappingResult.array.count != 0) {
    NSDictionary *data = mappingResult.array[0];       
    NSLog(@"data: %@", data);      
}else{
    NSLog(@"Unable to fetch data from: %@", path);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Error response': %@", error);
}];

除了使用NSPredict和筛选数据外,是否可以在映射时手动插入值(比如字符串)?

什么样的添加?源自哪些数据? - Wain
@Wain,我从网络服务中没有收到userID(字符串),我想每次手动添加它。 - A7madev
2个回答

6

你可以在完成块中修改映射结果的对象,但是这之后你需要明确保存上下文并且其他观察者也会收到保存通知。这是一个超级简单的方法。

或者你可以重写willSave方法或使用NSManagedObjectContextWillSaveNotification(后者是更好的选择)来触发自定义逻辑。你的更改将与RestKit更改内联进行,并且会自动保存。


非常感谢,有没有任何文档或教程可以帮助这两种方法? - A7madev
我在我的NSManagedObject中使用了willsave方法https://dev59.com/v2445IYBdhLWcg3waplH#5341212,但如果管理器在viewController中,我该如何保存一个值? - A7madev
你链接的答案对于 MO 方法都是很好的资源。我不太理解你关于视图控制器的问题。 - Wain
我在我的MainViewController中有userID,并且我正在调用Restkit管理器(上面的代码)在我的MainViewController中。链接的答案仅适用于NSManagedObject类本身内部的静态值,如果我想从viewController或AppDelegate设置值怎么办? - A7madev

2

使用以下方法解决了该问题

[[mappingResult set] setValue:value forKey:key]; 

在管理者的成功块中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接