2016-01-21 22 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() { 

    } 
} 
相关问题