我學習創建Objective-C中一個單獨的類和整個這個職位它使用GCD確保Singleton模式的強制執行來了。我對這個類中的實例init
方法以及它爲什麼在那裏感到困惑。Objective-C的單例類的實例初始化函數
看起來像有人試圖初始化MyManager
實例時會調用它,但爲什麼作者嘗試初始化父類的實例([super init]
)?與ObjC混亂
#import "MyManager.h"
@implementation MyManager
@synthesize someProperty;
#pragma mark Singleton Methods
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
- (id)init {
//what is purpose of initialising parent class (NSObject's) instance
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
}
return self;
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
}
@end
http://stackoverflow.com/questions/2956943/why -should-I-調用自超init和http://stackoverflow.com/questions/18693023/objective-c-questions-about-self-super-init你的問題是不相關真的單身,因爲我們幾乎總是在自定義初始化方法中調用[super init]。 – Larme