Swift Reference Variable from Specific Instance of Different Class

落花浮王杯 提交于 2019-12-22 09:51:37

问题


I'm new to Swift and iOS in general. I'm using Swift to write an app. This app has two files, ViewController.swift and BTService.swift.

ViewController.swift has a class ViewController of type UIViewController, and BTService.swift has a class BTService of types NSObject and CBPeripheralDelegate. I have a slider set up in the UIViewController class, and its value is assigned to variable currentValue.

Now, I want to be able to reference currentValue from within the BTService class. How can I go about doing this? I've noticed that if I define a variable, test, in the file ViewController before the class UIViewController, that I can reference test in BTService. But that's of no use to me since I can't (to my knowledge) get the slider value to be assigned to test unless test is defined within the UIViewController class.

Here's my ViewController and the currentValue variable definition.

class ViewController: UIViewController {


@IBOutlet var positionLabel: UILabel!
@IBOutlet var positionSlider: UISlider!
@IBOutlet var connectionLabel: UILabel!

@IBAction func sliderValChanged(sender: UISlider) {

    var currentValue = Float(positionSlider.value)

Any help would be greatly appreciated! Thanks.


回答1:


You can use NSUserDefaults to store data within your application and share it between view controllers.

In the example you give, you could store it like this:

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setFloat(Float(positionSlider.value), forKey: "sliderValue") // Write to NSUserDefaults
defaults.synchronize()

Then, whenever you need access to it in another file (or in this one), you can just call floatForKey:

if let currentValue: Float = defaults.floatForKey("sliderValue") {
    // Access slider value
} else {
    // Probably not saved
}



回答2:


Is your BTService a property within the UIViewController?

Could you use Key Value Observing (KVO)

Inside your UIViewController

override func viewDidLoad() {
    self.addObserver(self, forKeyPath: "positionSlider.value", options: .New, context: nil)
}

deinit() {
    self.removeObserver(self, forKeyPath: "positionSlider.value")
}

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if keyPath == "positionSlider.value" {
        // update service property
    }
}


来源:https://stackoverflow.com/questions/29045167/swift-reference-variable-from-specific-instance-of-different-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!