Should i write sqlite database file to Documents directory or Library/Caches?

后端 未结 2 1117
青春惊慌失措
青春惊慌失措 2021-01-03 04:19

I have read the Data Storage guidelines of Apple and am really confused as to where i should keep the sqlite database files i am creating in my app. I want to read from the

2条回答
  •  无人及你
    2021-01-03 04:46

    This may help you. Copying the database to the documents directory will be good enough, The files on bundle is read only, In some situation If you need to update at anytime the better way is copying the database at first if it not exists on the documents directory.

    The sample code for copying the database to the documents directory is follows:

    -(void) checkAndCreateDatabase {
    
        // Setup some globals
        NSString *databaseName = @"AnimalDatabase.sql";
    
        // Get the path to the documents directory and append the databaseName
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    
    
        // Check if the SQL database has already been saved to the users phone, if not then copy it over
        BOOL success;
    
        // Create a FileManager object, we will use this to check the status
        // of the database and to copy it over if required
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        // Check if the database has already been created in the users filesystem
        success = [fileManager fileExistsAtPath:databasePath];
    
        // If the database already exists then return without doing anything
        if(success) return;
    
        // If not then proceed to copy the database from the application to the users filesystem
    
        // Get the path to the database in the application package
        NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    
        // Copy the database from the package to the users filesystem
        [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    
        [fileManager release];
    }
    

    You can refer this Tutorial The files, contents on documents directory is read, write mode, so you can read the contents from the database.

提交回复
热议问题