在另一个类objective-c中保存一个类的实例
Posted
技术标签:
【中文标题】在另一个类objective-c中保存一个类的实例【英文标题】:Save instance of an class in another class objective-c 【发布时间】:2018-03-30 10:48:45 【问题描述】:在课堂上我正在与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】:将引用存储在数据成员中。在 Objective-C 中,这将类似于以下内容。我使用SomeClass
的类名并假设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
【讨论】:
嗯,不确定。那行_database = [database open]
给了我Implicit conversion of 'BOOL' (aka 'bool') to 'FMDatabase *' is disallowed with ARC
我将@interface
更改为@interface SomeClass () FMDatabase* _database; @end
我查找了 FMDatabase
的 api,所以我认为现在的代码更好。
感谢您的帮助以上是关于在另一个类objective-c中保存一个类的实例的主要内容,如果未能解决你的问题,请参考以下文章
根据用户选择将 UIPickerView 中的数据保存在 NSUserDefaults 中,并在另一个 ViewController Objective-C 中调用