我正在使用Restkit來擴展NSManagedObject類。 我知道rest套件本身具有從網絡抓取保存到核心數據的功能。但是,我不能使用該功能由於以下原因:Restkit-無法在NSManagedObject類上調用指定的初始值設定項
- 我的應用程序將從插座以及從靜止套件來獲取數據,所以我想一個集中的位置保存/刪除邏輯。
- 我的服務器沒有確認要休息協議,所以很多時候我都要發送POST請求,即使我真的想刪除服務器中的某些東西。
所以我想要做的是讓我的模型類擴展nsmanaged對象,並保存它,當我想。但我得到這個錯誤:
CoreData: error: Failed to call designated initializer on NSManagedObject class
有沒有辦法解決這個問題?
我從服務器獲取這樣的:
@implementation API_Login
+(void)performLoginWithEmail:(NSString*)email
withPassword:(NSString*)password
success:(void (^)(Token* user))success
failure:failureblock failure{
RKObjectManager * objectManager = [APIHelper getRestObjectManager];
RKObjectMapping *tokenMapping = [RKObjectMapping mappingForClass:[Token class]];
//add mapping for token
[tokenMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"token"]];
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:tokenMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:responseDescriptor];
// add mapping for error
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[Error class]];
[errorMapping addAttributeMappingsFromDictionary:@{@"message":@"message",@"badRequest":@"badRequest"}];
RKResponseDescriptor *errorResponseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:errorMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
[objectManager addResponseDescriptor:errorResponseDescriptor];
NSDictionary *queryParams = @{@"email" : email,
@"password" : password,
};
[objectManager postObject:nil
path:@"https://stackoverflow.com/users/api/login"
parameters:queryParams
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
Token* token = (Token*)[mappingResult firstObject] ;
// [AppDelegateHandle setToken:token];
success(token);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSArray* e = [[error userInfo] objectForKey:RKObjectMapperErrorObjectsKey];
Error *err = (Error*)[e objectAtIndex:0];
NSLog(@"%@",[err.badRequest allValues]);
failure(operation,error);
}];
}
@end
我Token類的樣子:
@interface Token : NSManagedObject
@property NSString* token;
@end
和我的API響應的樣子:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL3JlbWluZGVyLmRldlwvdXNlcnNcL2FwaVwvbG9naW4iLCJpYXQiOjE0Njg1OTM3NjYsImV4cCI6MTQ2OTE5Mzc2NiwibmJmIjoxNDY4NTkzNzY2LCJqdGkiOiIxMDc3ZjBhY2ViYTFjOWZjZWNhYjkyMzYyOTA0ZmI4NSJ9.I6FHJLCCHr3EHQa8HgaDqxQMjF1HVyA5AymPjvBGDrM"
}
當我改變令牌擴展NSObject而不是NSManagedObject,一切工作正常。問題是什麼?
可以決定何時保存數據嗎?我不想盲目保存數據。 –
否,RestKit將在完成映射後保存。您可以保存到不同的上下文/持久性存儲中,然後再進行合併。看起來像很多努力去... – Wain