gpt4 book ai didi

ios - 如何观察值(value)的变化并表现出来?在 swift

转载 作者:行者123 更新时间:2023-11-28 11:11:29 26 4
gpt4 key购买 nike

我有一个变量,它获取不同类中数组中对象的数量,我如何跟踪当前类中这个变量的变化?我做了很多不同的尝试,但都失败了。

var digitIndex: Int! {
set {
self.digitIndex = newValue
}
get {
return firstClass.indexesOfSelectedNodes().count
}
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &digitIndex {
if let newValue = change?[NSKeyValueChangeNewKey] {
print("newValue")
infoLabel.text = "\(newValue)"
}
}
}

最佳答案

1) 在你的代码中

var digitIndex: Int! {
set {
self.digitIndex = newValue
}
get {
return firstClass.indexesOfSelectedNodes().count
}
}

digitIndex 是计算属性!你不能在它自己的 setter 中设置 self.digitIndex!

这段代码,即使经过编译,也将永远运行:-)

var i: Int {
get {
return 10
}
set {
i = newValue
}
}

i = 100
print(i)

2) 如何使用 willSet 和 didSet(对于 STORED 属性)?

class C1 {}
class C2 {}

class C {
var objects: [AnyObject] = [C1(),C1(),C2()] {
willSet {
print(objects, objects.count, newValue)
}
didSet {
print(objects, objects.count)
}
}
func add(object: AnyObject) {
objects.append(object)
}
}

let c = C()
c.add(C1())
/*
[C1, C1, C2] 3 [C1, C1, C2, C1]
[C1, C1, C2, C1] 4
*/

var i: Int = 0 {
willSet {
print(newValue, "will replace", i)
}
didSet {
print(oldValue, "was replaced by", i)
}
}

i = 100
/*
100 will replace 0
0 was replaced by 100
*/

您可以根据自己的优势组合计算和存储的属性

// 'private' storage
var _j:Int = 0
var j: Int {
get {
return _j
}
set {
print(newValue)
if newValue < 300 {
_j = newValue
} else {
print(newValue, "refused")
}
}
}

print(j) // prints 0
j = 200 // prints 200
print(j) // prints 200
j = 500 // prints 500 refused
print(j) // prints 200

关于ios - 如何观察值(value)的变化并表现出来?在 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34767974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com