我的应用程序出现问题,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";

我在此函数中要求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是什么,它是:
文件://localhost/var/mobile/Applications/BE9A2982-BDC3-405D-A201-FB78E9E0790B/Documentscorebase.sqlite

我注意到它本身不是在“/ Documents”之后添加最后的“/”。
当我以这种方式创建网址时
NSURL *aStoreURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingFormat:@"/corebase.sqlite"]];

它似乎已经起作用,或者至少已通过了该部分。
此功能不应该自己添加该部分吗?
-(NSString*) applicationDocumentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

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

最佳答案

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

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

stringByAppending * PathComponent * 而不是stringByAppending * Format *
这个不错的小错误是通过自动完成功能带给您的:-)

为什么它在模拟器中起作用?我猜是因为您被允许在硬盘上的任何地方创建文件。因此,模拟器在您的Apps目录中创建了Documentscorebase.sqlite。您应该检查它是否在那里。

在iPhone上,您仅限于“文档”目录,并且不允许在任何地方创建文件。

关于core-data - CoreData“验证商店的网址时出错”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3832931/

10-10 17:00