ios - Access the same variable before and after value changes in different classes - Swift -
i've stucked on simple concept(i guess), have 2 viewcontrollers on storyboard have 2 classes, viewcontroller , viewcontroller2:
i have label whit default value (0), , when click on button want change value variable 10, , click on button "show" , print variable, i'm changing label , printing new value.
the real problem when want new variable value view, after change value if try print variable on second view variable return de default value(0)
viewcontroller
import uikit class viewcontroller: uiviewcontroller { var variable = "0" @iboutlet var defaultlabel: uilabel! @iboutlet var label1label: uilabel! @ibaction func setvalue(sender: anyobject) { setvalue() } @ibaction func getvalue(sender: anyobject) { getvalue() } override func viewdidload() { super.viewdidload() } func setvalue(){ variable = "10" defaultlabel.text = variable } func getvalue(){ print(variable) } override func didreceivememorywarning() { super.didreceivememorywarning() } } viewcontroller2
import uikit class viewcontroller2: uiviewcontroller { @iboutlet var label2label: uilabel! override func viewdidload() { super.viewdidload() } @ibaction func show(sender: anyobject) { print(viewcontroller().getvalue()) } override func didreceivememorywarning() { super.didreceivememorywarning() } } i've found post:
access variable in different class - swift
and think way find solution don't understand how call variable on viewcontroller2.
thanks.
use delegates!
here's example viewcontroller1 delegate viewcontroller2:
define protocol:
protocol variablemanager { func getvalue() -> int }then, in
viewcontroller1, modifygetvaluemethodviewcontroller1conforms protocol:class viewcontroller1: variablemanager { func getvalue() -> string { return variable } }now define variable in
viewcontroller2nameddelegate:class viewcontroller2 { var delegate: variablemanager? }in
prepareforseguemethod inviewcontroller1:override func prepareforsegue(segue: uistoryboardsegue) { if let identifier = segue.identifier { switch identifier { case "mysegueidentifier": let destination = segue.destinationviewcontroller as! 'viewcontroller2' destination.delegate = self default: break } } }now in
viewcontroller2, changeshowmethod:@ibaction func show(sender: anyobject) { if let delegate = delegate { let variable = delegate.getvalue() print(variable) }
delegation common, , important pattern. suggest read on it: https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/delegation.html
trying instantiate instant of viewcontroller1 inside viewcontroller2 not practice.

Comments
Post a Comment