【发布时间】:2015-04-20 17:12:28
【问题描述】:
仅当变量更改其值时,我需要我的应用程序将变量 myVariable 的值从类 firstClass 传递给另一个 secondClass。为此,我想到了使用 willSet 属性。但是,在 Swift 中,您不能在声明变量后使用它。
class firstClass: NSObject {
var myVariable = 0
func myFunction {
myVariable = 5
}
}
class secondClass: NSObject {
var otherClass = firstClass()
// How do I retrive the value of the variable right after its value changed?
}
我也想过添加一个NSNotification,但这无济于事,因为它没有传递值。 NSNotification 仅提醒其更改。
let myVariableNotification = NSNotification(name: "myVariableNotification", object: nil)
class firstClass: NSObject {
var myVariable = 0
func myFunction {
myVariable = 5
notificationCenter.postNotification(myVariableNotification)
}
}
class secondClass: NSObject {
var otherClass = firstClass()
NSNotificationCenter.defaultCenter().addObserverForName("myVariableNotification",
object: nil,
queue: NSOperationQueue.mainQueue()
usingBlock: { notification in
println("The variable has been updated!")
})
}
一旦变量改变了它的值,我似乎找不到传递变量的方法。我该怎么做?
【问题讨论】:
-
您想在从第一个视图控制器导航到第二个视图控制器时传递值,还是仅在该变量的值发生变化时传递值?
-
感谢您的评论!仅当
myVariable更改其值时。谢谢!