How do I add files to the resources folder in XCode?

后端 未结 2 1587
借酒劲吻你
借酒劲吻你 2021-01-06 00:34

I want to add a sqlite database to XCode 4 (applies to XCode 3 too). Tutorials state adding the .db file to the resources folder, and I suppose this gets copied to ~/Lib

2条回答
  •  孤街浪徒
    2021-01-06 01:12

    you have to start adding your db in your project-xcode, so it will be added in your bundle folder, where you can find it via code:

    [NSBundle mainBundle]
    

    It's the only folder where you can add files via xcode when you "build" your app (eventually with subfolders, but not "system" folders as "documents") now you just need to keep in mind that the main bundle folder is just "read only", so you cant use your db there with write privileges. So the normal way is:

    1) when you wanna use your db, check via code if it exists in the app:documents folder. Of course the first time it doesn't, so

    2) copy it from the main bundle

    - (BOOL)transferDb {
        NSError **error;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourData.db"]; 
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        if (![fileManager fileExistsAtPath: path])
        {
            NSString *bundle =  [[ NSBundle mainBundle] pathForResource:@"preferenze" ofType:@"plist"];
            [fileManager copyItemAtPath:bundle toPath:path error:error];
            return YES;
        }
        return NO;
    }
    

    3) use it (r/w) in the documents folder

    ps: and (of course) keep in mind that when you use/edit/write the db in iPhone/simulator, maybe adding records, the one in the main bundle and of course the one in your mac/project won't be updated, no records will be added to it, so if for any reason you delete your app on iPhone/simulator (or "clean all targets" by the xCode "build" menu) the check/copy method will copy the "virgin" db in the documents folder again, so you will loose all your changes...

提交回复
热议问题