When I run this :
@interface Database : NSObject {
sqlite3 *database;
}
+(void)openDatabase;
@end
@implementation Database
+(void)openDatabase
{
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *databaseNameandPath = [NSString stringWithFormat:@"%@/DatabaseSnax.sqlite",docDir];
NSString *databasePath=[[NSString alloc]initWithFormat:databaseNameandPath];
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK)
{
NSLog(@"Error when open the database");
}
[databasePath release];
}
I have this error: instance variable database accessed in class method
How I can solve this issue and I need to keep my method (open database) as a static method so I can use it by class name, for example:
[Database openDatabase];
One cannot possibly access instance variables from class methods. You may declare a global variable, however:
static sqlite3 *database;
// ...
+ (void) openDatabase {
sqlite3_open(filename, &database);
// ...
}
You're attempting to access database from a class method (which are different from instance methods).
Change that declaration from:
+ (void) openDatabase;
to
- (void) openDatabase;
and instantiate your Database object via the traditional alloc + init and you'll be on your way.
I like H2CO3's answer too (and +1 to him), but my answer (which is what most people have to do with Objective C objects) may be more practical for what you are trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With