Muhannad Dasoqie
Muhannad Dasoqie

Reputation: 313

Access instance variable via static method

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];

Upvotes: 3

Views: 3707

Answers (3)

ipmcc
ipmcc

Reputation: 29886

For reference, static means different things to different people/languages. Objective-C being mostly C plus a bunch of syntax enhancements, the keyword static in Objective-C has the same meaning as it does in C, which relates to the visibility of the symbol with respect to linking. This is subtly-but-importantly different from how Java and C# use the word static.

Objective-C doesn't have syntax for declaring "static" (in Java/C# parlance) or "class" variables. The runtime has "support" for them (witness the existence of: class_getClassVariable) but there's no syntax to declare them, so it's sort of a dead end. (If I had to guess, I'd bet that this feature exists in the runtime to support bridges to other languages/runtimes that use static/class variables.) As other people have suggested, the common way around this is to use global variables (or function statics (static in the C linkage sense.))

Upvotes: 2

Michael Dautermann
Michael Dautermann

Reputation: 89509

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.

Upvotes: 2

user529758
user529758

Reputation:

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);
    // ...
}

Upvotes: 3

Related Questions