来自不同类的特定实例的Swift参考变量 [英] Swift Reference Variable from Specific Instance of Different Class

查看:63
本文介绍了来自不同类的特定实例的Swift参考变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我是Swift和iOS的新手.我正在使用Swift编写应用程序.此应用程序有两个文件,ViewController.swiftBTService.swift.

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具有类型UIViewController的类ViewController,而BTService.swift具有类型NSObjectCBPeripheralDelegate的类BTService.我在UIViewController类中设置了一个滑块,并将其值分配给了变量currentValue.

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.

现在,我希望能够从BTService类中引用currentValue.我该怎么做呢?我注意到,如果我在类UIViewController之前的ViewController 文件中定义了变量test,则我可以引用test BTService.但这对我没有用,因为除非(在我的知识范围内)除非在UIViewController类中定义了test,否则我无法获得要分配给test的滑块值.

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.

这是我的ViewController和currentValue变量定义.

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.

推荐答案

您可以使用

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()

然后,只要需要访问另一个文件(或另一个文件)中的文件,就可以调用floatForKey:

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
}

这篇关于来自不同类的特定实例的Swift参考变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆