我正在使用 swift 开发 ios 应用程序。我正在使用 xcode7.0.1。与 TableView Controller 。我想在单击行时展开并在再次单击时折叠。我正在按照 gitHub 中的教程进行操作.现在我面临错误 Terminating app due to uncaught exception 'NSRangeException', reason: 'Cannot remove an observer
for the key path "frame" from <X.expandTips 0x145d8d20> because it is not registered as an observer.'
我希望以下代码行会导致问题。
我的 UITableViewCell 类代码:
func checkHeight(){
expandaple_view.hidden = (frame.size.height < expandTips.expandedHeight)
}
func WatchFrameChanges() {
addObserver(self , forKeyPath: "frame", options: .New, context: nil )
checkHeight()
}
func ignoreFrameChanges(){
removeObserver(self, forKeyPath: "frame")
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame"{
checkHeight()
}
}
在我的 TableViewController 代码中:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! expandTips) . WatchFrameChanges()
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! expandTips) . ignoreFrameChanges()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath == selectedIndexPath ){
return expandTips.expandedHeight
}else {
return expandTips.defaultHeight
}
}
我是 ios 的新手。我希望这一定是简单的问题。请有人帮我解决这个问题。
我不知道这里需要发布什么细节。如果我想添加更多详细信息,请发表评论。
最佳答案
从@Leandros 的评论中我找到了解决方案。只需使用 bool 变量跟踪观察者。
使用下面的代码,我找到了解决方案:
var frameAdded = false
func checkHeight(){
expanding_view.hidden = (frame.size.height < expandTips.expandedHeight)
}
func WatchFrameChanges() {
if(!frameAdded){
addObserver(self , forKeyPath: "frame", options: .New, context: nil )
frameAdded = true
}
}
func ignoreFrameChanges() {
if(frameAdded){
removeObserver(self, forKeyPath: "frame")
frameAdded = false
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "frame"{
checkHeight()
}
}
deinit {
print("deinit called");
ignoreFrameChanges()
}
关于ios - 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因 : 'Cannot remove an observer - ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32901926/