在Swift中使用UIAlertView,获得EXC_BAD_ACCESS

时间:2014-06-04 05:34:51

标签: ios xcode swift

首先,我非常清楚Xcode 6和Swift语言处于测试版并且容易出错;然而,这个特别的似乎是奇怪的,因为到目前为止我尝试的其他一切似乎都运行正常。

如果这不适合StackOverflow,我很乐意删除这个问题。

我开始玩Xcode 6 / Swift(准备发布),与我的想法相比,这是一种非常愉快的体验。话虽这么说,移植"培训"我喜欢的样式应用程序是由于EXC_BAD_ACCESS代码有问题而无法生成UIAlertView:

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

    var alert = UIAlertView(title: "Title", message: "Message", delegate: nil, cancelButtonTitle: "OK") // EXC_BAD_ACCESS here
    alert.show()
}

在创建UIAlertView的行上,我得到一个EXC_BAD_ACCESS因为在释放的实例上调用了[UIAlertView retain]

再一次,我将这个问题归结为测试版横幅,但是如果我做错了什么或其他人遇到类似的问题,我很好奇。

3 个答案:

答案 0 :(得分:29)

尝试以下代码

let alert = UIAlertView()
alert.title = "Title"
alert.message = "My message"
alert.addButtonWithTitle("Ok")
alert.show()

但是在iOS 8中

UIAlertView已弃用。因此,UIAlertController使用preferredStyle UIAlertControllerStyleAlert。它应该是:

var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

检查上面的代码,你是否得到同样的错误?

答案 1 :(得分:1)

来自Xcode 6.0 UIAlertView类:

  

UIAlertView已弃用。将UIAlertController与preferredStyle一起使用   取而代之的是UIAlertControllerStyleAlert。

在swift(iOS 8和OS X 10.10)上,你可以这样做:

var alert = UIAlertController(
    title: "Send",
    message: "You have successfully send your feedback.",
    preferredStyle: UIAlertControllerStyle.Alert
)
alert.addAction(UIAlertAction(
    title: "Ok",
    style: UIAlertActionStyle.Default,
    handler: nil
))
self.presentViewController(alert, animated: true, completion: nil)

答案 2 :(得分:-4)

2件事 你必须使用委托:自我 cancelButtonTitle以nil结尾

相关问题