我正在使用Restkit来扩展NSManagedObject。 我知道休息套件本身具有从网络提取中保存到核心数据的功能。但是,由于以下原因,我无法使用该功能:
所以我想做的是让我的Model类扩展nsmanaged对象,并在我想要的时候保存它。但是我得到了这个错误:
CoreData:错误:无法调用指定的初始化程序 NSManagedObject类
有办法解决这个问题吗?
我从这样的服务器获取:
@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:@"/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
我的令牌课程如下:
@interface Token : NSManagedObject
@property NSString* token;
@end
我的api响应如下:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL3JlbWluZGVyLmRldlwvdXNlcnNcL2FwaVwvbG9naW4iLCJpYXQiOjE0Njg1OTM3NjYsImV4cCI6MTQ2OTE5Mzc2NiwibmJmIjoxNDY4NTkzNzY2LCJqdGkiOiIxMDc3ZjBhY2ViYTFjOWZjZWNhYjkyMzYyOTA0ZmI4NSJ9.I6FHJLCCHr3EHQa8HgaDqxQMjF1HVyA5AymPjvBGDrM"
}
当我改变Token以扩展NSObject而不是NSManagedObject时,一切正常。问题是什么?
答案 0 :(得分:1)
这是因为您使用RKObjectMapping
而不是RKEntityMapping
,如果您使用NSManagedObject
的子类,则需要NSManagedObject
。
如果您不打算将其直接添加到上下文中,则不能使用NSDictionary
的子类。
如果您的请求只是一个令牌,那么我可能不会打扰RestKit,但在一般情况下我会映射到setValuesForKeysWithDictionary:
,其键与您的托管对象类相同,然后当您想要创建您可以执行此操作的托管对象,并使用.h
将数据“导入”给他们。