将 class 的实例保存到另一个 class objective-c

Save instance of an class in another class objective-c

在 class 中,我正在与 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)
    }

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

将引用存储在数据成员中。在 Objective-C 中,这将类似于以下内容。我正在使用 SomeClass 的 class 名称,并假设 FMDatabase 有一个 name 成员。

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