Swift单例模式 - Singleton

2016-08-10  本文已影响155人  拥抱月亮的大星星

1.单例如下

    class LibraryAPI {

     var name:String?
     static let  instance = LibraryAPI()
     var height:Double?

    }

这里static这个静态常量,只会被创建一次,而且在需要的时候才会被创建

2.验证


override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

      let apiSingle  = LibraryAPI.instance
        apiSingle.name = "笑话"
        apiSingle.height = 1.65

          print(apiSingle.name!)

       let button = UIButton.init(type: .Custom)
        button.frame = CGRectMake(100, 109, 100, 50)
        button.tag = 2222;
        view.addSubview(button)
        button.backgroundColor = UIColor.redColor()
        button .addTarget(self, action:#selector(ViewController.clickButton(_:)) , forControlEvents: .TouchUpInside)

    }


    func clickButton(sender:UIButton){

        let  api = LibraryAPI.instance
        print(sender.tag)
       if let name = api.name
       {
        print(name)
        }

      print(api.height)
    }

控制台输出:

笑话
2222
笑话
Optional(1.6499999999999999)

上一篇下一篇

猜你喜欢

热点阅读