Shipping a pre populated SQLite DB within the app. Path of the DB on startup

邮差的信 提交于 2020-01-16 08:55:16

问题


Maybe the title of the question is not very self-explanatory but I don't know how to summ it up.

I'm finishing an App which is basically a DB. I will ship a DB within the App. Everything works well but now I came to the problem. When the App is installed, it needs to create the database on the device. So, I dragged the DB to the "Supporting Files" folder in my Xcode project (still Xcode 4.1, by the way). I went to the AppDelegate.m file and looked for the (NSPersistentStoreCoordinator *)persistentStoreCoordinator{} method.

I substituted the line:

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Database.sqlite"];

for this code:

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Database.sqlite"];
NSLog(@"%@", storePath);

NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    // Put down default db if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Database" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
}

I got that from a tutorial by Ray Wenderlich.

The thing is that the compiler gives me a warning on the line

NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Database.sqlite"];

that tells me "NSURL may not respond to 'stringByAppendingPathComponent' and, actually, the App crashes because of that. interestingly enough, the example from the tutorial gives no warning whatsoever.

Somebody could give me a hand in what am I missing?

Thanks in advance!


回答1:


Are you sure [self applicationDocumentsDirectory] returns a NSString? If not, try this

- (NSString *)applicationDocumentsDirectoryString {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

And change [self applicationDocumentsDirectory] to [self applicationDocumentsDirectoryString]



来源:https://stackoverflow.com/questions/8143582/shipping-a-pre-populated-sqlite-db-within-the-app-path-of-the-db-on-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!