ios - Swift getter override non-computed variable -
in objective-c, easy , nice able do
- (uibutton *)backbutton{ if(!_backbutton){ _backbutton = [uibutton new]; } }
in swift however, when override property getter, it's called computed variable , every time self.backbutton
accessed, variable recomputed. following example illustrates nicely:
private var backbutton: uibarbuttonitem { let button = uibutton(frame: cgrect(x: 0, y: 0, width: self.view.frame.size.width*0.06, height: self.view.frame.size.width*0.06)) button.setimage(uiimage(named: "back_arrow"), forstate: uicontrolstate.normal) button.rac_signalforcontrolevents(uicontrolevents.touchupinside).subscribenext { (next: anyobject!) -> () in self.navigationcontroller?.popviewcontrolleranimated(true) return () } println("recalculating button") let item = uibarbuttonitem(customview: button) return item }
the println statement called every time access self.backbutton. addtionally, memory address printed out changes every time. understand that's nature of computed variables since not stored in memory.
is analogous way replicate exact same behavior seen in obj-c in swift? want way instantiate ui variable once without having put code in initialization method.
the best way create lazy variable, way initializer called 1 time, first time it's accessed.
lazy var backbutton:uibarbuttonitem = { let button = ... return button } ()
by using initializer block, can provide complex initialization of instance variable.
Comments
Post a Comment