iOS从数组导入魔法记录

问题描述:

您好我正在做一个同步功能,当从服务器收到JSON响应时更新数据库。我想进口才会发生,如果有不同的数据(新记录或更新现有记录)(为了提高性能)(使用coredatamagicalRecordiOS从数组导入魔法记录

这里是我的JSON解析器方法

- (void)updateWithApiRepresentation:(NSDictionary *)json 
{ 
    self.title = json[@"Name"]; 
    self.serverIdValue = [json[@"Id"] integerValue]; 
    self.year = json[@"Year of Release"]; 
    self.month = json[@"Month of Release"]; 
    self.day = json[@"Day of Release"]; 
    self.details = json[@"Description"]; 
    self.coverImage = json[@"CoverImage"]; 
    self.thumbnail = json[@"Thumbnail"]; 
    self.price = json[@"Buy"]; 

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
    [formatter setDateFormat:@"dd/MMMM/yyy"]; 

    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@/%@/%@",self.day,self.month,self.year]]; 
    self.issueDate = date; 
} 

和我导入方法

+ (void)API_getStampsOnCompletion:(void(^)(BOOL success, NSError  *error))completionBlock 
{ 
    [[ApiClient sharedInstance] getStampsOnSuccess:^(id responseJSON) { 

    NSManagedObjectContext *localContext = [NSManagedObjectContext MR_context]; 
    NSMutableArray *stamps = [[NSMutableArray alloc]init]; 
    [responseJSON[@"root"] enumerateObjectsUsingBlock:^(id attributes, NSUInteger idx, BOOL *stop) { 
     Stamp *stamp = [[Stamp alloc]init]; 
     [stamp setOrderingValue:idx]; 
     [stamp updateWithApiRepresentation:attributes]; 
     [stamps addObject:stamp]; 
    }]; 

    [Stamp MR_importFromArray:stamps inContext:localContext]; 

} onFailure:^(NSError *error) { 
     if (completionBlock) { 
      completionBlock(NO, error); 
     } 
    }]; 
} 

我收到提示

CoreData: error: Failed to call designated initializer on NSManagedObject class 'Stamp' 
2016-08-02 23:52:20.216 SingPost[2078:80114] -[Stamp setOrdering:]: unrecognized selector sent to instance 0x78f35a30 

我检查了我的Json解析器工作正常。问题在于我的导入方法。我不知道这个函数有什么问题。任何帮助非常感谢。谢谢!

错误消息清楚地描述了确切的问题。你这样做:

Stamp *stamp = [[Stamp alloc]init]; 

init不是NSManagedObject除非你在子类中添加init(你没有提到这样做)指定的初始化。您必须调用指定的初始化程序,即initWithEntity:insertIntoManagedObjectContext:NSEntityDescription上还有一个便利的工厂方法,名为insertNewObjectForEntityForName:inManagedObjectContext:。其中的任何一个都可以工作,但拨打init不会。

+0

嗨,感谢您的帮助,我正在与魔法记录库。是以上等于邮票*邮票= [邮票MR_createEntityInContext:localContext];?在添加新记录时避免重复的任何方法? –

+0

我没有使用魔法记录,所以我不能确定。 –

+0

那么你知道如何避免添加重复记录(在收到来自服务器的json响应之后)吗? –