CoreData"验证商店的网址时出错"

One*_*ake 2 core-data ios

我在我的应用程序中遇到问题,CoreData在模拟器中工作正常 - 但不在设备上.

我收到了

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";
Run Code Online (Sandbox Code Playgroud)

我在这个函数中调用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;
}
Run Code Online (Sandbox Code Playgroud)

我在"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"]];
Run Code Online (Sandbox Code Playgroud)

它似乎已经奏效,或至少已通过该部分.这个功能本身不应附加该部分吗?

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

它在模拟器中工作正常,什么是正确的做法?

Mat*_*uch 7

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
                  stringByAppendingFormat: @"corebase.sqlite"]];
Run Code Online (Sandbox Code Playgroud)

应该

NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] 
           stringByAppendingPathComponent: @"corebase.sqlite"]];
Run Code Online (Sandbox Code Playgroud)

stringByAppending*PathComponent*而不是stringByAppending*Format*.这个漂亮的小虫子是通过自动完成提供给你的:-)

为什么它在模拟器中工作?我猜是因为你被允许在硬盘上到处创建文件.因此模拟器在您的Apps目录中创建了Documentscorebase.sqlite.你应该检查它是否在那里.

在iPhone上,您仅限于Documents目录,不允许在任何地方创建文件.