gpt4 book ai didi

ios - 快速关闭属性错误访问(EXC_BAD_ACCESS)

转载 作者:行者123 更新时间:2023-11-28 09:20:16 27 4
gpt4 key购买 nike

我有一个带有 button_action 可选闭包的 Test 类:

class Test : CustomViewFromXib {
var button_action : (() -> ())?
@IBAction func button_pressed(sender: AnyObject) {
if let action = button_action {
action()
}
}
}

我是这样使用这个类的:

 let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = {
() -> () in
print("test")
}

我在行收到 EXC_BAD_ACCESS 错误:

test_view.button_action = {
() -> () in
print("test")
}

我不知道为什么,因为我只想设置初始值。是否可以这样做?

更新:

我明白,没有任何属性或方法不能从我的对象中调用。不仅是闭包,还有字符串(例如)。

更新 2:

这是我重现问题的小代码示例。我想我的初始化程序有问题...... https://www.dropbox.com/s/1d8fvxm0es9b5n4/TestInit.zip

(XCode 6 测试版 5)

最佳答案

写代码

let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = {
() -> () in
print("test")
}

代替

let test_view = Test(frame: CGRect.nullRect)
self.view.addSubview(test_view)
test_view.button_action = { [unowned self]
() -> () in
print("test")
}

这是确切的详细理论答案 Shall we always use [unowned self] inside closure in Swift https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

关于ios - 快速关闭属性错误访问(EXC_BAD_ACCESS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25285324/

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