在Swift中尝试初始化UIActionSheet时出现EXC_BAD_ACCESS错误

9

我的程序能够成功编译,但是当我点击按钮时就会崩溃。以下是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 (code=2, address=0x0)

我尝试将 let 改为 var,用不同的模拟器运行,但结果仍然相同。

2个回答

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 Delegate

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

1
谢谢,它可以工作!顺便说一下,我把“var”改成了“let”,它也可以工作! - lazyd3v
嗯,actionSheet(myActionSheet:UIActionSheet!,clickedButtonAtIndex buttonIndex:Int)不起作用。 代码是相同的,但我将这些行添加到类实现中。 - lazyd3v
请正确检查委托。我遇到了这段代码,然后才发布的。 - Kumar KL
1
我错过了“myActionSheet.delegate = self”这一行。现在一切都正常了。谢谢。 - lazyd3v
我曾经遇到过同样的问题,当我使用NSLog()记录控制器视图运行代码时,会出现随机崩溃。看起来带参数的构造函数存在某种严重的错误。 - Juan Carlos Ospina Gonzalez

0

你必须以 nil 结束 otherButtonTitles 参数。例如,在你的情况下应该这样写:

otherButtonTitles:"camera", "libary", nil

这不是特定于Swift,Objective-C中也是一样的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接