iOS Magical record import from array

流过昼夜 提交于 2020-01-25 20:27:18

问题


Hi I'm making a synchronise function that update database when receive JSON response from server. I want the import only take place if there are different data (new record or update existing record) (To increase performance) (Using coredata and magicalRecord)

Here is my JSON parser method

- (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;
}

And my import method

+ (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);
        }
    }];
}

I'm getting 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

I have checked my Json parser is working fine. The problem is with my import method. I don't know what wrong with the function. Any help is much appreciate. Thanks!


回答1:


The error message clearly describes the exact problem. You do this:

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

But init is not the designated initializer for NSManagedObject unless you added init in your subclass (which you didn't mention doing). You must call the designated initializer, which is initWithEntity:insertIntoManagedObjectContext:. There's also a convenience factory method on NSEntityDescription called insertNewObjectForEntityForName:inManagedObjectContext:. Either of those will work, but calling init will not.



来源:https://stackoverflow.com/questions/38725256/ios-magical-record-import-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!