swift中的loadNibNamed应返回Singleton对象

时间:2016-05-06 08:17:04

标签: ios swift swift2 singleton

我想加载Nib(自定义视图的UIView的子类),但对象应该是单例。我使用下面的代码在Objective C上做同样的事情,但现在我在Swift 2.2中编写代码

任何人都可以帮助我在Swift中转换此代码或执行此操作的任何其他方法。

+(LoaderView *)sharedInstance;
{
    static LoaderView * _sharedCommonInstance;
    @synchronized(self)
    {
        if (!_sharedCommonInstance)
        _sharedCommonInstance = [[[NSBundle mainBundle] loadNibNamed:@"LoaderView" owner:self options:nil] objectAtIndex:0];

        return _sharedCommonInstance;
    }
}

我的尝试

class var sharedInstance: LoaderView {
       struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: LoaderView? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = NSBundle.mainBundle().loadNibNamed("LoaderView", owner: self, options: nil)[0] as? LoaderView
        }
        return Static.instance!
    }

但通过此方法应用程序崩溃,请检查我的屏幕截图enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

class LoaderView {
static let sharedCommonInstance = NSBundle.mainBundle().loadNibNamed("LoaderView", owner: self, options: nil)[0] as UIView

}

答案 1 :(得分:0)

有几种方法。你可以试试这些

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print(LoaderView.sharedInstance)
        print(LoaderView.sharedInstanceA)
        print(LoaderView.sharedInstanceB)
}

我在ViewController中调用ViewDidLoad

df <- data.frame(id = c(1,2,3,4), 
                 lon = c(-81.0000, -80, -81.0001, -79), 
                 lat = c(42, 40, 42, 41) )
library(dplyr)
df %>% 
  group_by(lon=round(lon, 3), lat=round(lat, 3)) %>% 
  summarise(count=n())
# Source: local data frame [3 x 3]
# Groups: lon [?]
# 
#     lon   lat count
#   (dbl) (dbl) (int)
# 1   -81    42     2
# 2   -80    40     1
# 3   -79    41     1

控制台打印

output

请记住在xib文件中设置“LoaderView”类

enter image description here

您也可以在这里引用http://krakendev.io/blog/the-right-way-to-write-a-singleton