我编写了一个代码来解析一些JSON并通过魔法记录将数据保存到数据库:
2.5
以上代码不保存到持久存储。我有一段时间没有使用魔法记录,似乎保存与过去不同。我现在如何保存我的数据?
答案 0 :(得分:1)
如果您想使用saveWithBlock
,则代码应为
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
Time *newTime = [Time MR_createEntityInContext:localContext];
newTime.distance = ...
...
}
另一种方法是将saveWithBlock
替换为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];
有关CoreData的更多了解使用MegicalRecord,我建议您阅读本教程
http://code.tutsplus.com/tutorials/easy-core-data-fetching-with-magical-record--mobile-13680