你好我的问题很简单我必须不断地检查一个布尔值是否是真还是假,我迄今尝试是使用:如何经常检查bool的值是否为真/假? SWIFT
override func update(_ currentTime: TimeInterval)
功能迅速,这是方式快速和一旦它检查值将不断重复的行动,即使我只希望它只执行一次行动,所以基本上我说的是,我想要做的就是检查布尔值是否为真或者一次假,然后停止检查直到它再次改变。请帮忙,谢谢。
你好我的问题很简单我必须不断地检查一个布尔值是否是真还是假,我迄今尝试是使用:如何经常检查bool的值是否为真/假? SWIFT
override func update(_ currentTime: TimeInterval)
功能迅速,这是方式快速和一旦它检查值将不断重复的行动,即使我只希望它只执行一次行动,所以基本上我说的是,我想要做的就是检查布尔值是否为真或者一次假,然后停止检查直到它再次改变。请帮忙,谢谢。
地产观察家
您可以使用属性观察员斯威夫特完成你所需要的...这里是文档说这些是什么:
地产观察者观察和在变化作出反应物业的价值 。每次属性值为 时,即使新值与属性当前的 值相同,也会调用属性观察者。
有willSet
和didSet
财产观察员:
willSet被称为值存储之前。
didSet在新值被存储后立即调用。
解决你的问题,你可以做这样的事情:
var myProperty:Int = 0 {
willSet {
print("About to set myProperty, newValue = \(newValue)")
}
didSet{
print("myProperty is now \(myProperty). Previous value was \(oldValue)")
}
}
您可以实现一个或两个你的财产属性观察员。
getter和setter
作为替代,您可以使用一个存储的属性getter和setter方法来解决问题:
private var priv_property:Int = 0
var myProperty:Int{
get {
return priv_property
}
set {
priv_property = newValue
}
}
计算属性不实际存储的值。相反,他们提供了一个getter和一个可选的setter来间接检索和设置其他属性和值。
你应该使用观察者或回调。阅读下面的评论,看看@ Whirlwind的回答。下面的解决方案并不是真正的推荐,因为它效率低下,可能会使代码复杂化。但是,如果您想要或需要在update()
中执行此操作,请按以下步骤操作:
// Assume stored property
// It might be an API call and so on
var boolToWatch = false
var lastValueOfWatchedBool: Bool?
var lastCheck: TimeInterval = 0
let checkInterval = 1.0 // check every second
override func update(_ currentTime: TimeInterval) {
// In case boolToWatch is an expensive API call might be good to
// check less frequently
if currentTime - lastCheck > checkInterval {
lastCheck = currentTime
// Check for the initial case
if lastValueOfWatchedBool == nil {
lastValueOfWatchedBool = boolToWatch
}
// Detect change
if boolToWatch != lastValueOfWatchedBool {
lastValueOfWatchedBool = boolToWatch
// Do what you need to do when the value changed here
print("I feel different!")
}
}
}
请问您能解释一下吗? bool_的这个值是什么?它是同一个班级还是别的什么? – ziya