在另一个类objective-c中保存类的实例

时间:2018-03-30 10:48:45

标签: ios objective-c fmdb

在课程中,我正在与fmdb

建立数据库连接

像(伪代码):

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

如何在班级中保存对database的引用?

1 个答案:

答案 0 :(得分:1)

将引用存储在数据成员中。在Objective-C中,这将类似于以下内容。我使用的是SomeClass的班级名称,并假设FMDatabasename成员。

// 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