Lê Khánh Vinh Lê Khánh Vinh - 1 year ago 96
iOS Question

iOS Magical record import from array

Hi I'm making a synchronise function that update database when receive

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

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download