简体   繁体   中英

Saving in Magical Record?

I have written a code to parse some JSON and save data to database via magical record:

NSMutableArray *resultsArray = [NSMutableArray array];
NSArray *timesArray = JSON[@"results"];
for (NSDictionary *record in timesArray) {
    Time *newTime = [Time MR_createEntity];
    newTime.distance = record[@"distance"];
    newTime.time = record[@"time"];
    newTime.date = [[MMXFormatter instance] dateFromString:record[@"date"]];
    newTime.createdAt = [[MMXFormatter instance] dateFromString:record[@"createdAt"]];
    newTime.updatedAt = [[MMXFormatter instance] dateFromString:record[@"updatedAt"]];
    [resultsArray addObject:newTime];
}
[MagicalRecord saveWithBlock:nil];

The above code does not save to persistent store. I haven't used Magical Record in a while, and seems saving is different from what it used to be. How do i save my data now?

If you want to use saveWithBlock , the code should be

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    Time *newTime = [Time MR_createEntityInContext:localContext];
    newTime.distance = ...
    ...
}

another way is just replace saveWithBlock with MR_saveToPersistentStoreAndWait

NSMutableArray *resultsArray = [NSMutableArray array];
NSArray *timesArray = JSON[@"results"];
for (NSDictionary *record in timesArray) {
    Time *newTime = [Time MR_createEntity];
    newTime.distance = record[@"distance"];
    newTime.time = record[@"time"];
    newTime.date = [[MMXFormatter instance] dateFromString:record[@"date"]];
    newTime.createdAt = [[MMXFormatter instance] dateFromString:record[@"createdAt"]];
    newTime.updatedAt = [[MMXFormatter instance] dateFromString:record[@"updatedAt"]];
    [resultsArray addObject:newTime];
}
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

For More Understanding about CoreData With MegicalRecord I would recommend you to go through this tutorial

http://code.tutsplus.com/tutorials/easy-core-data-fetching-with-magical-record--mobile-13680

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM