核心数据填充在模拟器中但不移动到设备

时间:2013-10-08 23:01:14

标签: ios sqlite core-data

我在堆栈上找到了很多解释和帮助,但到目前为止,没有运气。

差不多,我的myapp.sqlite(我预先填充的)在模拟器上工作正常,但是当我在iPad上运行时,它是空的。

所以在尝试不同的事情之后,这是我最接近的事情:

  • 我将sqlite数据库复制到Bundle中,但我将其移动到Library文件夹。

在我的AppDelegate上,我这样做:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSLog(@"Starting to save the DB to another location");

    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"myDB.sqlite"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) {
        // database doesn't exist in your library path... copy it from the bundle
        NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"myDB" ofType:@"sqlite"];
        NSError *error = nil;

        if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) {
            NSLog(@"Error: %@", error);
        }
    }


    return YES;
}

然后在PersistentStoreCoordinator上,我这样做

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

    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"myDB.sqlite"];

//    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"naccApp.sqlite"];
//    NSURL *storeURLLocal = [[NSBundle mainBundle] URLForResource:@"myDB" withExtension:@"sqlite"];

    NSURL *storeURL = [NSURL URLWithString:targetPath];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return _persistentStoreCoordinator;
}

当我尝试使用DB(fetchRequest)时,出现错误:

CoreData SQL仅存储支持文件URL(已获得/var/mobile/Applications/2EB2AADD-DF9D-475F-A05E-BB138502471F/Library/myDB.sqlite)。

信息很明确,但我在这里几乎都尝试了所有的帮助,但仍然没有。

毋庸置疑,我是Core Data的新手,所以请原谅无知。

哦,我正在使用xCode 5。

THX

1 个答案:

答案 0 :(得分:4)

NSURL *storeURL = [NSURL URLWithString:targetPath];

应该是:

NSURL *storeURL = [NSURL fileURLWithPath:targetPath];

这样您就可以生成文件网址而不是网址。