保存对UIManagedObjectDocument的更改时,iPhone App崩溃

时间:2013-10-02 21:21:03

标签: ios core-data thread-safety

我有一个带有两个独立的TableViewControllers(" TVC")的应用程序,它们访问相同的CoreData SQL表。用户通过按下父ViewController中的按钮来呼叫TVC。但是,第一个TVC通过调用NSManagedObject子类写入CoreData的记录未被第二个TVC识别。我想我正在创建我的UIManagedDocument的单独实例,因此开始在父VC中实例化UIManagedDocument并将文档传递给相应的TVC。

然而,现在,当我在向其写入记录后尝试保存文档时,即使我在最初实例化文档的主线程上,应用程序也会崩溃。

我是以错误的方式来做这件事的吗?

这是父ViewController

//
#import "ITrackViewController.h"
#import "AthleteSearchTVController.h"

@interface ITrackViewController()

@end

@implementation ITrackViewController

@synthesize myFirstName = _myFirstName;
@synthesize myLastName  = _myLastName;

@synthesize athleteDatabase = _athleteDatabase;


-(void) setAthleteDatabase:(UIManagedDocument *)athleteDatabase
{
    if(_athleteDatabase != athleteDatabase)
    {
        _athleteDatabase = athleteDatabase;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    if (!self.athleteDatabase) {  // for demo purposes, we'll create a default database if none is set

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"Default Athlete Database"];
    NSLog(@"url for dataBase is %@.",url);
    // url is now "<Documents Directory>/Default Athlete Database"
    self.athleteDatabase = [[UIManagedDocument alloc] initWithFileURL:url]; // setter will create this for us on disk
    }

}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"BeginSearch"]) {
        NSLog(@"firstName is %@ and lastName is %@.",firstName.text, lastName.text);

        NSString *checkFirstName = [firstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *checkLastName = [firstName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

        if ([checkFirstName length] < 1 || [checkLastName length] < 1) {
        NSLog(@"Must include a value for both first and last names.");
        } else {
            [self dismissKeyboard:sender];
            myFirstName  = firstName.text;
            myLastName   = lastName.text;

            UIManagedDocument *sharedAthleteDataBase = [self sharedDatabase];

            NSString *searchName = [myFirstName stringByAppendingString:@"%20"];
            searchName = [searchName stringByAppendingString:myLastName];

        NSLog(@"searchName is %@ before segue.",searchName);

            [segue.destinationViewController nameToSearchFor:searchName andUIManagedDoc:sharedAthleteDataBase];
        }

    }
}

-(IBAction)dismissKeyboard:(id)sender
{
[lastName endEditing:YES];
[firstName endEditing:YES];
}

- (UIManagedDocument *) sharedDatabase
{

    __block UIManagedDocument *managedDocument = nil;

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"AthleteData"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.athleteDatabase.fileURL path]]) {
        // does not exist on disk, so create it
        [self.athleteDatabase saveToURL:self.athleteDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {

            if(success){
                NSString* isMainThread;
                if ([NSThread isMainThread]) {
                    isMainThread = @"on main thread.";
                } else isMainThread = @"but not on main thread";
                NSLog(@"athleteDatabase did not exist, now created %@", isMainThread);
                managedDocument = self.athleteDatabase;
            } else {
                NSLog(@"Error creating athleteDatabase");
            }
        }];
    } else if (self.athleteDatabase.documentState == UIDocumentStateClosed) {
        // exists on disk, but we need to open it

        [self.athleteDatabase openWithCompletionHandler:^(BOOL success) {

            if(success){
                NSString* isMainThread;
                if ([NSThread isMainThread]) {
                    isMainThread = @"on main thread.";
                } else isMainThread = @"but not on main thread";
                NSLog(@"athleteDatabase was closed, is now open %@", isMainThread);
                managedDocument = self.athleteDatabase;

            } else NSLog(@"Error opening closed athleteDatabase");

        }];
    } else if (self.athleteDatabase.documentState == UIDocumentStateNormal) {
        // already open and ready to use
        managedDocument = self.athleteDatabase;
    }

    return managedDocument;
}

@end

TVC调用NSManagedObject子类首先从基于Web的API检索数据,然后将其写入CoreData。

- (void)fetchAthleteSearchResultsIntoDocument:(UIManagedDocument *)document
                                  whereNameIs:(NSString *)athleteName

{
    dispatch_queue_t fetchQ = dispatch_queue_create("Athlete fetcher", NULL);
    dispatch_async(fetchQ, ^{
        NSString* isMainThread;
        if ([NSThread isMainThread]) {
            isMainThread = @"on main thread.";
        } else isMainThread = @"but not on main thread";
        NSLog(@"Preparing to get records %@", isMainThread);
        NSArray *athleteRecords;
        athleteRecords = [AthleticNetDataFetcher searchForMyAthleteWithName:athleteName];

        [document.managedObjectContext performBlockAndWait:^{ // perform in the NSMOC's safe thread (main thread)
            int iCount = 0;
            for (NSDictionary *athleteInfo in athleteRecords) {

                [ResultsForAthleteSearch resultsWithAthleteInfo:athleteInfo inManagedObjectContext:document.managedObjectContext
                                           numberForSorting:iCount];
                iCount = iCount + 1;
                // table will automatically update due to NSFetchedResultsController's observing of the NSMOC
            }

            NSString* isMainThread;
            if ([NSThread isMainThread]) {
                isMainThread = @"on main thread.";
            } else isMainThread = @"but not on main thread";
            NSLog(@"Preparing to save results %@", isMainThread);

            [document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];

        }];
    });

}

模拟器在调用[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL]时崩溃;

下面部分给出的日志表示我在主线程上。我无法弄清楚为什么会崩溃。如果我注释掉saveToURL调用并依赖自动保存,它不会崩溃。

2013-10-02 13:46:22.459 iTrackTest[14989:c07] url for dataBase is file://localhost/Users/Phlipo/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/53E19DAE-6D2B-4B7F-A633-55C2BCA95AC5/Documents/Default%20Athlete%20Database/.

2013-10-02 13:46:31.031 iTrackTest[14989:c07] url for dataBase is file://localhost/Users/Phlipo/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/53E19DAE-6D2B-4B7F-A633-55C2BCA95AC5/Documents/Default%20Athlete%20Database/.

2013-10-02 13:46:31.039 iTrackTest[14989:61f] Preparing to get records but not on main thread

2013-10-02 13:46:31.065 iTrackTest[14989:c07] athleteDatabase was closed, is now open on main thread.
2013-10-02 13:46:31.620 iTrackTest[14989:61f] [AthleticNetDataFetcher executeSearchRequest:] received {
.
[A bunch of data in JSON format].
.
}


2013-10-02 13:46:31.633 iTrackTest[14989:c07] Preparing to save results on main thread.
2013-10-02 13:47:23.258 iTrackTest[16150:3f07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores.  It cannot perform a save operation.'

当我在TVC中实例化MOD时,我没有遇到此NSPErsistence错误。我可能需要更明确的DataBase Helper吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

暂时取消了这一点,但这是我想出来的。

我记得在Android中我使用过SQL辅助类。对于简单的应用,Paul Hegarty建议采用这种方法,并提出一些注意事项。

Tim Roadley's tutorial是关于此主题的绝佳资源。

相关问题