问题
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.
回答1:
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
extension UserDefaults {
var indexA: Int {
get {
return integer(forKey: "indexA")
}
set {
set(newValue, forKey: "indexA")
}
}
}
usage:
To load it
let indexA = UserDefaults.standard.indexA
To set/change it
UserDefaults.standard.indexA = 10
回答2:
You should:
Add set public or internal modifier for
indexin order to use it outside a classCreate an instance of
ViewControllerRetrieve
indexfrom an instancelet vc = ViewController() print("index: \(vc.index)")
回答3:
let vc = ViewController()
print("index: \(vc.index)")
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
In ViewDidLoad of ViewController you set viewcontrollerInstall = self
And in your new class call :
print("Index is \(viewcontrollerInstall.index)")
回答4:
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.
来源:https://stackoverflow.com/questions/35078674/swift-access-variable-in-viewcontroller