Where does iPhone simulator put data files?

2019-09-13 02:39发布

问题:

If I compile my iPhone App with a database that has been built into the bundle what path do I have to use to find the file so that I can open it, as in:

FMDatabase* db = [FMDatabase databaseWithPath:@"/???/database.sqlite"]; 

回答1:

Inside your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

set the following code:

databaseName=@"yourfileName.sqlite";    
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    [self checkAndCreateDatabase];

-(void) checkAndCreateDatabase {

BOOL success;


NSFileManager *fileManager = [NSFileManager defaultManager];

success = [fileManager fileExistsAtPath:databasePath];

if(success) return;
else
    printf("NO File found");

NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

}



回答2:

You can use like this regardless of simulator or device. Please dont forget to add db file to your project folder and add to your bundle.

#define DATABASE @"databasefile.sqlite"


NSArray *documentPaths      = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir      = [documentPaths objectAtIndex:0];
databasePath                = [[NSString alloc] initWithString:[documentsDir stringByAppendingPathComponent:DATABASE]];


标签: iphone xcode