简体   繁体   English

崩溃后核心数据为空

[英]Core data empty after crash

I'm simulating a crash to test out how my app responds and noticed that my core data is empty when relaunching the app. 我正在模拟崩溃以测试我的应用程序如何响应,并注意到重新启动应用程序时我的core data为空。 Until now, using core data and NSFetchRequest has been working perfectly - I can terminate the app or turn off the phone and the data always remains. 到目前为止,使用核心数据和NSFetchRequest一直运行良好-我可以终止应用程序或关闭电话,并且数据始终保留。 I'm using core data to store the URLS to audio files stored in NSFileManager . 我正在使用核心数据将URLS存储到NSFileManager存储的音频文件中。 When I relaunch the app, I can see that the files are still in NSFileManager but NSFetchRequest returns a count of zero and my tableview is empty. 重新启动应用程序时,我可以看到文件仍在NSFileManagerNSFetchRequest返回的计数为零,并且我的表tableview为空。 Anyone experience this before? 有人以前经历过吗?

EDIT: I've been simulating crashes using these two lines: 编辑:我一直在使用这两行模拟崩溃:

    NSArray *array = @[];
    array[1];

In viewDidLoad of my main view controller, I call the following: 在主视图控制器的viewDidLoad中,我调用以下命令:

self.managedDocument = [OSManagedDocument getInstance];
[self.managedDocument setUpDocument];  

managedDocument is a singleton that contains all my methods for data management. managedDocument是一个单例,其中包含我所有的数据管理方法。

@property (nonatomic, strong) NSManagedObjectContext * managedObjectContext;


+(OSManagedDocument*) getInstance
{
    static OSManagedDocument* _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[OSManagedDocument alloc] init];
    });
    return _instance;
}

-(void) setUpDocument
{

    if(self.document == nil)
    {
        NSFileManager * fileManager = [NSFileManager defaultManager];
        NSURL * documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
        NSString * documentName = @"MyRecordings";
        self.url = [documentsDirectory URLByAppendingPathComponent:documentName];
        self.document = [[UIManagedDocument alloc] initWithFileURL:self.url];


        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[self.url path]];

        if(fileExists)
        {
             [self.document openWithCompletionHandler:^(BOOL success) {
                if(success)
                {
                    [self documentIsReady];

                }

             }];
        }
        else
        {
             [self.document saveToURL:self.url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
                if(success)
                {
                     [self documentIsReady];

                }
                else
                {
                    NSLog(@"Fail");
                }

            }];

        }
    }
}

-(void) documentIsReady
{

    if(self.document.documentState ==UIDocumentStateNormal)
    {
        self.managedObjectContext = self.document.managedObjectContext;
        NSLog(@"context is ready");
        [self fetchControllerFiles];
        [self recordingCount];
    }
}

-(int) recordingCount
{

    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Recording"];
    NSError *error;
    request.predicate = nil;
    request.sortDescriptors =nil;
    NSArray * recordings = [self.managedObjectContext executeFetchRequest:request error:&error];

    NSLog(@"recordings count %lu", (unsigned long)recordings.count);
    return (int)[recordings count];
}

When my app relaunches after a crash, I call the following: 当我的应用在崩溃后重新启动时,我调用以下命令:

 -(void) appBecameActive:(NSNotification *)notification
 {
     self.managedDocument = [OSManagedDocument getInstance];
 }

I call this method to add to core data 我称此方法添加到核心数据

-(void) saveRecording:(NSMutableDictionary*) recordPackage inManagedObjectContext:(NSManagedObjectContext*) context
{

    Recording * recording = [NSEntityDescription insertNewObjectForEntityForName:@"Recording" inManagedObjectContext:context];

    recording.trackTitle = [recordPackage objectForKey:@"track label"];
    recording.audioURL = [[recordPackage objectForKey:@"audioURL"] absoluteString];
    recording.timeAdded = [NSDate date];
    recording.waveData = [recordPackage objectForKey:@"waveData"];
    recording.minAmpl = [recordPackage objectForKey:@"minAmpl"];
    recording.recordingNumber = [recordPackage objectForKey:@"recordingNumber"];


}

I've been counting on auto-save to take care of the saving and it worked fine until I started forcing crashes to see how the app recovered. 我一直指望自动保存来完成保存工作,并且在我开始强制崩溃以查看应用程序如何恢复之前,它一直工作良好。 Since the data was disappearing after every crash, I decided to try and save manually and it worked. 由于每次崩溃后数据都消失了,所以我决定尝试手动保存并起作用。 Now the data appears even after a forced crash. 现在,即使在强制崩溃之后,数据也会出现。 I'm assuming this means auto-saving wasn't occurring in time. 我假设这意味着没有及时进行自动保存。 Not exactly sure how to explain it, but saving the context manually resolved my issue. 不确定如何解释,但是手动保存上下文解决了我的问题。

[self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
    if(success)
    {
        NSLog(@" NEW FILE SAVED");
    }
    else
    {
        NSLog(@"FAIL TO SAVE");
    }

}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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