尝试在Swift中初始化UIActionSheet时的EXC_BAD_ACCESS

时间:2014-06-13 05:22:55

标签: ios xcode swift uiactionsheet

我的程序编译成功,但是当我按下按钮时,它会崩溃。这是viewController.swift:

import UIKit

class ViewController: UIViewController, UIActionSheetDelegate{

@IBOutlet var button:UIButton

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func buttonPressed(AnyObject) {
    let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "libary")
    choice.showInView(self.view)
}
}

此行显示错误:

let choice = UIActionSheet(title: "Select source", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles:"camera", "library")

这是错误文字:

EXC_BAD_ACCESS(代码= 2,地址= 0x0)

我试图将let切换到var,在不同的模拟器上运行它,但结果是一样的。

2 个答案:

答案 0 :(得分:6)

试过,但无法弄清楚异常。最后我得到了这样的解决方案:

  var myActionSheet:UIActionSheet = UIActionSheet()

        var title : String? = "Select Source"
        myActionSheet.title  = title
            myActionSheet.delegate = self
        myActionSheet.addButtonWithTitle("camera")
        myActionSheet.addButtonWithTitle("Library")
        myActionSheet.addButtonWithTitle("Cancel")

        myActionSheet.cancelButtonIndex = 2 
        myActionSheet.showInView(self.view)

UIActionSheet委托

func actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int){
        println("the index is %d", buttonIndex)
    }

答案 1 :(得分:0)

你必须用nil结束otherButtonTitles参数。例如,在您的情况下,它应该是:

otherButtonTitles:"camera", "libary", nil

它不是Swift特有的,它在objective-c中也是一样的。