I have a View Controller with a button, an index, and a function thats called when the button is pressed, here is an example of the code:
View Controller:
func buttonPressed(){
index++
}
Then i have a class in which i want to access and print the index from the View Controller
Class:
print("Index is \(ViewController().index)")
Obviously this doesn't work, does anyone know how I can access this? I can't really instantiate it because its a ViewController as well as it will not be the same index.I think.
Try passing the reference of the view controller which has the index and button to the class where you want to access it.
From there on you can access the same index value and other properties of that view controller in that class.
is not correct because vc in there is not viewController,that contain button you clicked. It has to be declared again
In case, you should have a singleton of ViewController(ex:
viewcontrollerInstall
) and put in anywhere so you can access InViewDidLoad
ofViewController
you setviewcontrollerInstall = self
And in your new class call :
You can save your index to NSUserDefaults or to a plist file. Try using a getter and a setter to make it persist automatically as follow:
Xcode 8.3.3 • Swift 3.1.1
usage:
To load it
To set/change it
You should:
Add set public or internal modifier for
index
in order to use it outside a classCreate an instance of
ViewController
Retrieve
index
from an instance