【发布时间】:2010-01-03 09:18:07
【问题描述】:
我对标准 NSObject 的 init() 方法有疑问。我写了一个类(EFAPersistence),它是 NSObject 的子类。 EFAPersistance 有一个名为 efaDatabase 的属性。
EFAPersistence.h
@interface EFAPersistence : NSObject {
FMDatabase * efaDatabase;
}
@property (assign) FMDatabase * efaDatabase;
每次创建 EFAPersistance 实例时,我都想从我的 AppDelegate 中为 efaDatabase 分配一个值。
EFAPersistence.m
@implementation EFAPersistence
@synthesize efaDatabase;
- (id)init {
if (self = [super init]) {
efaDatabase = [[NSApp delegate] efaDatabase];
}
return self;
}
@end
这种分配方式行不通。但是,如果我将代码放在正常的方法中,它就会起作用。所以我确信 efaDatabase 已在我的 AppDelegate 中正确实例化。它只是在我的 init() 方法中不起作用。这就是为什么我觉得 NSApp 在 init() 方法中不起作用的原因。
这就是重要的 AppDelegate 代码的样子。
AppDelegate.h
@interface AppDelegate : NSObject <NSApplicationDelegate> {
FMDatabase * efaDatabase;
}
AppDelegate.m
- (id)init {
if (self = [super init]) {
NSString * databasePath =
[[NSBundle mainBundle] pathForResource:@"efa" ofType:@"sqlite"];
self.efaDatabase = [FMDatabase databaseWithPath:databasePath];
if (![efaDatabase open]) {
NSLog(@"Couldn't open database: %@", databasePath);
// TODO: Create a database here
}
self.db = [[EFAPersistence alloc] init];
}
return self;
}
如您所见,我正在调用 init 方法。我还通过使用 NSLog() 确认了这一点。 init() 被调用。我试图在 EFAPersistence 中分配的属性也是在调用 init() 之前创建的。
总结一下:
如何在 init() 方法中完成这项工作,这样我就不必在所有 EFAPersistence 方法中编写样板代码?
【问题讨论】:
-
语法说明:在 Objective-C 中引用实例方法的正确方法是 -method:name:include:colons:,而不是 method()。例如,-init 或 -databaseWithPath:,而不是 init() 或 databaseWithPath()。
标签: objective-c cocoa