2010-09-30 69 views
2

我在應用程序中遇到了問題,CoreData的工作方式與應用程序在模擬器中一樣 - 但不在設備上。CoreData「驗證存儲的URL的錯誤」

我收到

2010-09-30 12:45:07.500 CoreDataTutorial_iOS[130:307] Unresolved error Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x1412a0 {NSUnderlyingException=Error validating url for store}, { 
    NSUnderlyingException = "Error validating url for store"; 

我呼籲PersistentStoreCoordinator在這個函數(會拋出上述錯誤):

-(NSPersistentStoreCoordinator*)persistentStoreCoordinator 
{ 
    if(persistentStoreCoordinator_ != nil) 
     return persistentStoreCoordinator_; 

    NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:@"corebase.sqlite"]]; 
    NSError *anError = nil; 

    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if(![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:aStoreURL options:nil error:&anError]) 
    { 
     NSLog(@"Unresolved error %@, %@", anError, [anError userInfo]); 
     abort(); 
    } 

    return persistentStoreCoordinator; 
} 

我設置一個破發點,在「objc_exception_throw 「,以查看aStoreURL是什麼,它是: file://localhost/var/mobile/Applications/BE9A2982-BDC3-405D-A201-FB78E9E0790B/Documentscorebase.sqlite

我注意到它本身並沒有在「/ Documents」之後添加最後的「/」。 當我創建了一個URL這樣

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:@"/corebase.sqlite"]]; 

這似乎已經奏效,或者至少得以通過的那部分。 該功能不應該附加該部分本身嗎?

-(NSString*) applicationDocumentsDirectory 
{ 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
} 

它在模擬器中正常工作,什麼是正確的做法?

回答

7
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
        stringByAppendingFormat: @"corebase.sqlite"]]; 

應該

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
      stringByAppendingPathComponent: @"corebase.sqlite"]]; 

stringByAppending * PathComponent *代替stringByAppending * 格式*。 這個漂亮的小bug是通過自動完成給你帶來的:-)

爲什麼它在模擬器中工作?我猜是因爲你可以在硬盤上的任何地方創建文件。所以模擬器在您的Apps目錄中創建了Documentscorebase.sqlite。你應該檢查它是否在那裏。

在iPhone上,您僅限於Documents目錄,並且不允許在任何地方創建文件。