簡體   English   中英

在Swift中使用UIAlertView,獲得EXC_BAD_ACCESS

[英]UIAlertView in Swift, getting EXC_BAD_ACCESS

首先,我非常清楚Xcode 6和Swift語言都是Beta版,容易出錯; 然而,這個特別的東西似乎有點奇怪,因為到目前為止我嘗試的其他東西似乎都很好。

如果這不適合StackOverflow,我很樂意刪除這個問題。

我開始玩Xcode 6 / Swift(准備發布),與我的想法相比,這是一次非常愉快的體驗。 話雖這么說,移植我喜歡做的“訓練”風格應用程序的一個問題是我似乎無法生成UIAlertView,因為EXC_BAD_ACCESS有問題的代碼是:

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]

再一次,我正在將這個問題歸結為beta橫幅,但是如果我做錯了什么或者其他人遇到過類似的問題,我很好奇。

請嘗試以下代碼

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

但是在iOS 8中

UIAlertView已棄用。 因此,使用UIAlertControllerpreferredStyleUIAlertControllerStyleAlert 它應該是:

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)

檢查上面的代碼,你是否得到相同的錯誤?

從Xcode 6.0 UIAlertView類:

UIAlertView已棄用。 使用UIAlertController而不是UIAlertControllerStyleAlert的preferredStyle。

在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件你必須使用委托:self cancelButtonTitle以nil結尾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM