2013-05-16 26 views
2

@interfaceinit在這個單例類中有什麼用處?

// 
// Created by macbook on 31.05.12. 
// 
// To change the template use AppCode | Preferences | File Templates. 
// 


#import <Foundation/Foundation.h> 


@interface CESettings : NSObject 
+ (CESettings *)sharedInstance; 

- (void)save; 
@end 

@implementation

// 
// Created by macbook on 31.05.12. 
// 
// To change the template use AppCode | Preferences | File Templates. 
// 


#import "CESettings.h" 

@interface CESettings() 
@property(nonatomic, strong) NSUserDefaults *userDefaults; 
@end 

@implementation CESettings 
@synthesize userDefaults = _userDefaults; 

#pragma mark - Singleton 
static CESettings *_instance = nil; 
+ (CESettings *)sharedInstance { 
    @synchronized (self) { 
     if (_instance == nil) { 
      _instance = [self new]; 
     } 
    } 

    return _instance; 
} 

- (id)init { 
    self = [super init]; 
    if (self) { 
     self.userDefaults = [NSUserDefaults standardUserDefaults]; 
    } 

    return self; 
} 

#pragma mark - Methods 
- (void)save { 
    [self.userDefaults synchronize]; 
} 

@end 

我有一個應用程序用於設置類。該類有一個創建單例和init方法的方法。兩者都有什麼用?..?我認爲如果sharedInstance方法存在,那麼不需要init ...請糾正我,如果我錯了。 任何幫助表示讚賞。

回答

7

init方法是在[self new]的調用中被new調用的方法。它本質上是一樣的

_instance = [[CESettings alloc] init]; 

,但需要較少的打字和避免硬編碼的CESettings類的名稱。

使用dispatch_once,像這樣實現單更好的辦法:

+ (CESettings*)sharedInstance 
{ 
    static dispatch_once_t once; 
    static CESettings *_instance; 
    dispatch_once(&once,^{ _instance = [self new]; }); 
    return _instance; 
} 
+0

謝謝..忘了它。 :/ –

+0

@AnkitSrivastava你必須接受。 :D – rptwsthi

+0

@rptwsthi 15分鐘計時器之前,我可以接受任何東西。 –

3

NSObject文檔:

+ (id)new

分配接收類的新實例,將其發送一個初始化 消息,並返回初始化的對象。

你在你的單身創作者的方法,這反過來將分配一個新的實例,並把它的init消息調用[self new]

+0

謝謝..忘了它。 :/ –

1

的sharedInstance類方法僅適用於分配和INITING一個對象,然後總是返回負責任的。

你沒有經歷這種方法,你可以調用的alloc初始化自己,這也將工作

因此,init是需要保持怎樣的alloc的語義/初始化應該工作

相關問題