gpt4 book ai didi

ios - 为什么var的setter for KVO崩溃了(Swift 2.2)?

转载 作者:行者123 更新时间:2023-12-01 20:05:47 24 4
gpt4 key购买 nike

我正在使用KVO进行手动通知,但是为什么代码由于以下原因而崩溃:

线程1:点击时,EXC_BAD_ACCESS(代码= 2,地址= 0x7fff577bcfa8)
跑?

请参见下面的代码:
ChildrenViewController.swift(要观察的类)

import UIKit
class ChildrenViewController: UIViewController {

dynamic var name: String? {
get {
return ""
}

set {
willChangeValueForKey("name")
guard let value = newValue else {return}
self.setValue(value, forKey: "name") //crashed here!SAID "Thread 1:EXC_BAD_ACCESS (code=2, address=0x7fff577bcfa8)"
didChangeValueForKey("name")
}

}

dynamic var age = 0

var child: ChildrenViewController?

override class func automaticallyNotifiesObserversForKey(key: String) -> Bool {
if key == "name" {
return false
}
return super.automaticallyNotifiesObserversForKey(key)
}

}
ViewController.swift(观察者)
import UIKit

private var child1Context = 1

class ViewController: UIViewController {

var child1 = ChildrenViewController()

override func viewDidLoad() {
super.viewDidLoad()

self.child1.setValue("George", forKey: "name")
self.child1.setValue(15, forKey: "age")
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

child1.addObserver(self, forKeyPath: "name", options: [.New,.Old], context: &child1Context)
child1.addObserver(self, forKeyPath: "age", options: [.New, .Old], context: &child1Context)

self.child1.name = "Michael" //set the name String
self.child1.setValue(20, forKey: "age")
}

override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)

self.child1.removeObserver(self, forKeyPath: "name")
self.child1.removeObserver(self, forKeyPath: "age")
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &child1Context {
if keyPath == "name" {
print("The name of FIRST has been changed, \(change)")
}
if keyPath == "age" {
print("The age of FIRST has been changed, \(change)")
}
}
}

}

最佳答案

您可以通过以下行在中设置name的值,它是自己的设置者:

self.setValue(value, forKey: "name")

为什么不能这样做:
private var _name: String?//create private variable to hold value
dynamic var name: String? {
get {
return _name
}

set {
willChangeValueForKey("name")
guard let value = newValue else {return}
_name = value
didChangeValueForKey("name")
}
}

关于ios - 为什么var的setter for KVO崩溃了(Swift 2.2)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38875215/

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