2016-01-21 27 views
-6

任何人都可以幫我把這段代碼轉換成Swift嗎?Swift中的SharedInstance

這裏我在Objective-C代碼中提到.h.m

AbcUIViewController。我想在我的Swift代碼中執行此方法。 S怎麼可能?

Abc.h

+ (Abc*)sharedInstance; 
- (void) startInView:(UIView *)view; 
- (void) stop; 

Abc.m

static Abc*sharedInstance; 

+ (Abc*)sharedInstance 
{ 
    @synchronized(self) 
    { 
     if (!sharedInstance) 
     { 
      sharedInstance = [[Abc alloc] init]; 
     } 

     return sharedInstance; 
    } 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 

    } 
    return self; 
} 

@end 
+0

你必須告訴我們你試過什麼,並讓我們知道你遇到了什麼問題。 – Cristik

+8

如果你打算在其中開發,你仍然需要學習Swift。 – Cristik

+0

爲什麼這個問題被標記爲過於寬泛並擱置?它是一個如何在Swift中創建單例的簡單問題。 – crashoverride777

回答

2

在迅速的最好和最乾淨的辦法就是這個

static let sharedInstance = ABC() 

無需structsclass variable,這仍然是一個有效的辦法做它,但它的n非常喜歡Swift。

不知道你想使用單例爲UIViewControllers但是在斯威夫特一般Singleton類是這樣的

class ABC { 

    static let sharedInstance = ABC() 

    var testProperty = 0 

    func testFunc() { 

    } 
} 

,比你的其他類,你只想說

let abc = ABC.sharedInstance 

abc.testProperty = 5 
abc.testFunc() 

或直接打電話

ABC.sharedInstance.testProperty = 5 
ABC.sharedInstance.testFunc() 

另外作爲一個備註,如果你ü如果你是一個Singleton類,並且你有一個初始化程序,你應該使它私人化

class ABC { 

    static let sharedInstance = ABC() 

    private init() { 

    } 
} 
相關問題