为什么这个 swift 按钮设置会崩溃?
Why is this swift button setup crashing?
我正在尝试以编程方式将按钮及其操作方法添加到视图。关键是动作方法应该与按钮在同一个文件中,这样我就可以将文件放到其他应用程序中。当点击按钮时,我希望执行操作方法,但它却崩溃了。它只给出 EXC_BAD_ACCESS 而没有日志输出。
这是一个简化的测试应用,只有两个 类:ViewController 和 BlueButton:
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let button = BlueButton(mainView: view)
button.installButton()
}
}
class BlueButton: NSObject {
var mainView: UIView
init(mainView: UIView) {
self.mainView = mainView
}
func installButton() {
let button = UIButton(frame: CGRect(x: 25, y: 100, width: 150, height: 50))
button.setTitle("Tap Me", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
button.addTarget(self, action: "someAction", forControlEvents: .TouchUpInside)
mainView.addSubview(button)
}
func someAction() {
println("this is someAction")
}
}
回溯显示没有任何帮助。它以 objc_msgSend 结尾。我尝试了很多不同的方法来重新排列代码,但没有任何效果。我添加了一个 'All Exceptions' 断点,但它没有被击中。我在 someAction 方法上放置了一个断点,只是为了确保它没有被调用——它没有被调用。有人可以告诉我发生了什么事吗?
您的 BlueButton
实例在 viewDidAppear
returns 时被释放,因为不再有对它的强引用。
点击按钮时,它会尝试引用该实例,但它已被释放,这会导致崩溃。
您可以通过多种方式解决问题。最简单的方法是在 ViewController
class 中创建一个 属性 并将 BlueButton
存储在其中,只要按钮可见即可。
我正在尝试以编程方式将按钮及其操作方法添加到视图。关键是动作方法应该与按钮在同一个文件中,这样我就可以将文件放到其他应用程序中。当点击按钮时,我希望执行操作方法,但它却崩溃了。它只给出 EXC_BAD_ACCESS 而没有日志输出。
这是一个简化的测试应用,只有两个 类:ViewController 和 BlueButton:
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let button = BlueButton(mainView: view)
button.installButton()
}
}
class BlueButton: NSObject {
var mainView: UIView
init(mainView: UIView) {
self.mainView = mainView
}
func installButton() {
let button = UIButton(frame: CGRect(x: 25, y: 100, width: 150, height: 50))
button.setTitle("Tap Me", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
button.addTarget(self, action: "someAction", forControlEvents: .TouchUpInside)
mainView.addSubview(button)
}
func someAction() {
println("this is someAction")
}
}
回溯显示没有任何帮助。它以 objc_msgSend 结尾。我尝试了很多不同的方法来重新排列代码,但没有任何效果。我添加了一个 'All Exceptions' 断点,但它没有被击中。我在 someAction 方法上放置了一个断点,只是为了确保它没有被调用——它没有被调用。有人可以告诉我发生了什么事吗?
您的 BlueButton
实例在 viewDidAppear
returns 时被释放,因为不再有对它的强引用。
点击按钮时,它会尝试引用该实例,但它已被释放,这会导致崩溃。
您可以通过多种方式解决问题。最简单的方法是在 ViewController
class 中创建一个 属性 并将 BlueButton
存储在其中,只要按钮可见即可。