Copying data to the Application Data folder on the iPhone

后端 未结 3 1927
Happy的楠姐
Happy的楠姐 2020-12-29 17:29

I am in the process of (finally) loading my App onto an iPhone device for testing. So far I have only tested the App in the simulator. The application is data-centric and us

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 18:04

    As Alex said, you have to add your database file as a resource to your project. This will instruct Xcode to bundle your database file in your .app. That file however is read-only, it's up to you to copy it over to your apps document folder (on the device or simulator, same thing), where it becomes writable basically.

    Here's the code that I use for this kind of thing below. The nice thing about this code is that it will automatically refresh the writable copy in your apps document folder whenever you change the "main" copy bundled in the .app. Use 'pathLocal' to open your (writable) database...

    The function below returns YES when the operation was successful (whether a copy was needed or not). You're free to change that with whatever suits you :)

    NSString *pathLocal, *pathBundle;
    
    // Automatically copy DB from .app bundle to device document folder if needed
    - (BOOL)automaticallyCopyDatabase {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];
        pathLocal = [documentsDir stringByAppendingPathComponent:@"mydb.sqlite"];
        pathBundle = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *localAttr = [fileManager fileAttributesAtPath:pathLocal traverseLink:YES];
        BOOL needsCopy = NO;
        if (localAttr == nil) {
            needsCopy = YES;
        } else {
            NSDate *localDate;
            NSDate *appDBDate;
            if (localDate = [localAttr objectForKey:NSFileModificationDate]) {
                NSDictionary *appDBAttr = [fileManager fileAttributesAtPath:pathBundle traverseLink:YES];
                appDBDate = [appDBAttr objectForKey:NSFileModificationDate];
                needsCopy = [appDBDate compare:localDate] == NSOrderedDescending;
            } else {
                needsCopy = YES;
            }
        }
        if (needsCopy) {
            NSError *error;
            BOOL success;
            if (localAttr != nil) {
                success = [fileManager removeItemAtPath:pathLocal error:&error];
            }
            success = [fileManager copyItemAtPath:pathBundle toPath:pathLocal error:&error];
            return success;
        }
        return YES;
    }
    

提交回复
热议问题