核心数据不持久:使用magicrecord

Posted

技术标签:

【中文标题】核心数据不持久:使用magicrecord【英文标题】:Core Data not persisting: Using magicalrecord 【发布时间】:2015-05-14 16:23:57 【问题描述】:

好的,

我正在使用 Magicalrecord 实现核心数据。我的应用程序在第一次加载时会下载一堆信息。然后将该数据保存到核心数据中。这是在 AppDelegate 文件中完成的。但是,每当我的应用程序进入后台或被终止时,数据就会丢失。下面是使用 options 方法的 didFinishLaunching:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

NSLog(@"My app is starting");


[MagicalRecord setupAutoMigratingCoreDataStack];

//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"AGM_DataSetup"]) 



    NSError* jsonError;
    NSArray* json;

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];

    if (internetStatus == NotReachable) 
        NSLog(@"Offline");
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"static" ofType:@"json"];
        NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
        json = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
     else 
        NSLog(@"Online");
        NSData* data = [NSData dataWithContentsOfURL:
                        aWaterURL];
        json = [NSJSONSerialization
                JSONObjectWithData:data
                options:kNilOptions
                error:&jsonError];
    

    if (!jsonError) 

        [MagicalRecord cleanUp];
        NSString* folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error = nil;
        for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error])
        
            [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
            if(error)
            
                NSLog(@"Delete error: %@", error.description);
            
        

        [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"Anglers411.sqlite"];

        NSLog(@"Initial Data Load");


        for (id jsonArea in json) 

            // Create an area
            Area *area = [Area MR_createEntity];
            area.name  = [jsonArea objectForKey:@"name"];
            area.bulletDescription  = [jsonArea objectForKey:@"bulletDescription"];
            area.uid  = [jsonArea objectForKey:@"id"];

            NSArray* jsonLocations  = [jsonArea objectForKey:@"locations"];

            for (id jsonLocation in jsonLocations) 

                // create a location
                Location *location = [Location MR_createEntity];
                location.uid = [jsonLocation objectForKey:@"id"];
                location.name = [jsonLocation objectForKey:@"name"];
                location.desc = [jsonLocation objectForKey:@"desc"];
                location.directions = [jsonLocation objectForKey:@"directions"];
                location.bulletDescription = [jsonLocation objectForKey:@"bulletDescription"];
                location.area = area;

                NSArray* jsonBugs  = [jsonLocation objectForKey:@"bugs"];

                for (id jsonBug in jsonBugs) 
                    Bug *bug = [Bug MR_createEntity];
                    bug.name = [jsonBug objectForKey:@"name"];
                    bug.spring = [jsonBug objectForKey:@"spring"];
                    bug.summer = [jsonBug objectForKey:@"summer"];
                    bug.fall = [jsonBug objectForKey:@"fall"];
                    bug.winter = [jsonBug objectForKey:@"winter"];
                    bug.location = location;
                
            

        

        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) 
            if (success) 
                NSLog(@"You successfully saved your context.");
             else if (error) 
                NSLog(@"Error saving context: %@", error.description);
            
        ];


        // Set User Default to prevent another preload of data on startup.
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AGM_DataSetup"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    


return YES;

这是我在 applicationDidEnterBackground 和 ApplicationWillTerminate 中使用的方法:

- (void)saveContext 
[MagicalRecord cleanUp];


感谢您对此的任何帮助。我已经阅读了这里的所有magicrecord non-persist 问题,但没有找到任何有效的方法。

保重,

【问题讨论】:

【参考方案1】:

对不起,

经过进一步探索,我发现设置2个不同名称的核心数据堆栈通常是行不通的,如果您希望它们是同一个堆栈...我已经更正了这个。

【讨论】:

以上是关于核心数据不持久:使用magicrecord的主要内容,如果未能解决你的问题,请参考以下文章

核心数据模板:运行之间不持久的数据

核心数据持久存储协调器不存在

CBD Store 作为 iOS 中核心数据的持久存储

创建一个核心日期实体实例但不希望它被存储(非持久性)

NSPersistentStoreCoordinator 在 ios iOS 中没有持久存储(架构不匹配或迁移失败)核心数据

需要一个持久的地方来存储我的核心数据存储的备份