Ross M.
Ross M.

Reputation: 313

Swift Reference Variable from Specific Instance of Different Class

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.

Upvotes: 3

Views: 824

Answers (2)

slik
slik

Reputation: 5221

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
    }
}

Upvotes: 0

AstroCB
AstroCB

Reputation: 12367

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
}

Upvotes: 1

Related Questions