【问题标题】:EXC_BAD_ACCESS when trying to init UIActionSheet in Swift尝试在 Swift 中初始化 UIActionSheet 时出现 EXC_BAD_ACCESS
【发布时间】:2014-06-13 05:22:55
【问题描述】:

我的程序编译成功,但是当我按下按钮时,它崩溃了。这是 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,在不同的模拟器上运行,结果都是一样的。

【问题讨论】:

    标签: ios xcode swift uiactionsheet


    【解决方案1】:

    尝试过,但无法找出异常。最后我得到了这样的解决方案:

      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)
        }
    

    【讨论】:

    • 谢谢,它有效!顺便说一句,我将“var”更改为“let”,它也可以工作!
    • 嗯,actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) 不起作用。代码是一样的,但我将这些行添加到类实现中。
    • 正确检查代表。遇到了这段代码,然后只有我发布了
    • 我错过了“myActionSheet.delegate = self”这一行。现在一切正常。谢谢
    • 当我 NSLog() 运行代码的控制器视图时,我遇到了同样的问题和随机崩溃。看起来带参数的构造函数中存在某种严重的错误。
    【解决方案2】:

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

    otherButtonTitles:"camera", "libary", nil
    

    它不是 Swift 特有的,在 Objective-c 中也是如此。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2019-07-25
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      相关资源
      最近更新 更多