1
votes

I am creating a SQLite3 database project in Xcode for Iphone. I am using the Simulator 3.1.2. Although I have attached the database file in the Resources group of the project and passing the name alright in the Appdelegate file and also creating a local editable copy using:

// Copy the database from the package to the user's filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:self.dbPath error:nil];

... but every time I run the example to check, it creates a new database file in the filesystem with the name I supply under the Macintosh HD folder. I am supplying the databasename like so: @"testdb.sqlite" and my init database routine looks like this:

- (id) initsql: (NSString*) name {
    if(self = [super init])
    {
        // Override point for customization after app launch    
        self.logging = -1;
        self.dbName = name;

        // Get the path to the documents directory and append the database name
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        self.dbPath = [documentsDir stringByAppendingPathComponent:self.dbName];

        // 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:self.dbPath];

        // If the database already exists then return without doing anything
        if(!success)
        {
            // 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:self.dbName];

            // Copy the database from the package to the users filesystem
            [fileManager copyItemAtPath:databasePathFromApp toPath:self.dbPath error:nil];

            [fileManager release];
        }
        int result = sqlite3_open([self.dbName UTF8String], &database);
        if(result != SQLITE_OK)
        {
            sqlite3_close(database);
            [self logmsg:[[NSString alloc] initWithFormat:@"Couldn't open database: %@", self.dbName] level:2];
            return self;
        }
        [self logmsg:[[NSString alloc] initWithFormat:@"Database opened: %@", self.dbName] level:-1];
    }
    return self;
}

Any tips as to what may be going wrong?

1

1 Answers

1
votes

Solved.

int result = sqlite3_open([self.dbName UTF8String], &database);

... had to be ...

int result = sqlite3_open([self.dbPath UTF8String], &database);