我对标准NSObject的init()方法有问题。我写了一个类(EFAPersistence),它是NSObject的一个子类。 EFAPersistance有一个属性,称为efaDatabase。NSObject初始化方法的问题
EFAPersistence.h
@interface EFAPersistence : NSObject {
FMDatabase * efaDatabase;
}
@property (assign) FMDatabase * efaDatabase;
每次EFAPersistance的一个实例被创建我想分配efaDatabase从我的AppDelegate的值。
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的所有方法?
语法note:在Objective-C中引用实例方法的正确方法是-method:name:include:colons :, not method()。例如,-init或-databaseWithPath :,而不是init()或databaseWithPath()。 – 2010-01-04 02:42:47