I have an app which pretty much follows the method described here. The key code is as follows:
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@interface FailedBankDatabase : NSObject {
sqlite3 *_database;
}
+ (FailedBankDatabase*)database;
- (NSArray *)failedBankInfos;
@end
#import "FailedBankDatabase.h"
#import "FailedBankInfo.h"
@implementation FailedBankDatabase
static FailedBankDatabase *_database;
+ (FailedBankDatabase*)database {
if (_database == nil) {
_database = [[FailedBankDatabase alloc] init];
}
return _database;
}
- (id)init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"banklist"
ofType:@"sqlite3"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(@"Failed to open database!");
}
}
return self;
}
- (void)dealloc {
sqlite3_close(_database);
[super dealloc];
}
Now, the app works with one database as expected. But, I want to be able to switch to a different database when the user touches a button. I have the button handler and logic OK, and I store the name of the database to be used and can retrieve it. But, no matter what I do, I always get the same (original) database being called. I fear that the handle associated with _database, a object of type sqlite3, in the example is not being changed properly, so I don’t open the database properly. How should I go about changing this? You can’t re-init a singleton, but I need to change what’s stored in it, in this case _database. Thanks.
EDIT: I would add that if I ask for _database is a pointer. So I need to open a new database (and close the first I guess) and give the new database a new address in the process.
I had the same problem, but couldn’t modify the database (they were used in other projects).
So, I created a method called useDatabase:, that close the previous connection, and open a new one.
The steps :
Your – (id)init remains the same
In FailedBankDatabase, you create a method that close and open the database with the name of the new database
At the very beggining (for example in appDidFinishLaunching), you call the singleton once
, so that it is first initialised.
Then, when you want to change the .sqlite used, you can call :
I think you can do this when you don’t have to change the database very often. In my case, I use this once at the very first screen, with 3 buttons, where I will choose wich database will be used.
For more complicated cases, for exemple involving multithreading, you should not do that since it closes the connection for a little time, while it is used elsewhere.
Hope it helps,
Jery