I have a class called SqliteImageAccess that is going to have various methods that provide support for some sqlite functionality. I have a local class variable of type sqlite3 and a class method called opendb. This class method should do one thing and one thing only. Open the database.
The only sticky point here is that my sqlite3 object is going to be an instance variable and Objective-C, for whatever weird reason, doesn’t let you access instance variables inside of class methods. Obviously, in other languages, when you instantiate a class, the constructor of that class might call a private method to initialize some local class variables(local private variable perhaps). I want to do the same thing with my sqlite3 object through the equivalent of an Objective-C class constructor method. Perhaps someone can help because I am stuck on this one.
Obviously in another class I can instantiate the SqliteImageAccess class and then call the opendb method. That works fine. I don’t want to have to do that. When i instantiate the class the goal is so that the class will handle the opening of the database automatically.
Lastly, with the other methods that are going to be available to do other sqlite work(inserts, etc), i am going to need full access to the db object. thanks in advance for any help.
//SqliteImageAccess.h
@interface SqliteImageAccess : NSObject {
}
+(void)opendb; //class method
@end
//SqliteImageAccess.m
#import "SqliteImageAccess.h"
@implementation SqliteImageAccess
static sqlite3 *db;
+(void)initialize{
[self opendb];
}
+(void)opendb{
int open = sqlite3_open("/Users/csmith/RPG/cws.sqlite3", &db);
if(open == SQLITE_OK){
NSLog(@"Database was opened successfully");
}
else {
NSLog(@"open result = %d", open);
}
}
@end
In the interface you declare opendb as a class methode (+) but your are using – in the implementation. Normaly you should get a warning, that your class implementation isn’t complete. Change the – to + to implement opendb as a class method and call it via
Further, + (void)initilaize is only called once during program life cycle, in think you would like to go with
Seeing one more thing, your sqlite3 property is declared as an instance variable, so you can’t call it from a class method! You have to move the sqlite3 *db from the .h to the .m file as
after @implementation.