Search code examples
iosobjective-cfmdb

Save instance of an class in another class objective-c


In a class I am establishing a database connection with fmdb

Something like (pseudo code):

// someClass.m
- (void)sameDatabase:(NSString *)database{
    if (database is the same as before)
    {
        // call method and access reference previously saved in class (someClass) in else statement
    } else {
        ...
        [database open]; //FMDB
        // save reference to database in class (someClass)
        // call method and access reference saved in class (someClass)
    }

How would I save the reference to database in the class?


Solution

  • Store the reference in a data member. In Objective-C, this would be something like the following. I’m using a class name of SomeClass and assuming that FMDatabase has a name member.

    // someClass.m
    
    @interface SomeClass () // In the .m file, this is for defining private members
    {
        FMDatabase* _database; // Convention is to have private data start with _
    }
    @end
    
    @implementation SomeClass
    
    - (void)sameDatabase:(NSString *)database 
        if ([_database.databasePath isEqualToString:database]) {
            // call method and access reference previously saved in class (someClass) in else statement
        } else {
            ...
            // I can't say what this line should be, so I just used your code.
            // It would depend on the database you are using.
           _database = [FMDatabase databaseWithPath: database];
           [_database open];
        }
    }
    
    @end