swift - 线程 1 : exc_bad_instruction(code=exc_i386_invop, 子代码 = 0x0)/ fatal error :索引超出范围

标签 swift xcode multithreading

我正在尝试开发一个应用程序,现在我想通过 2 个不同的 UIPickerViews 的输入来编辑标签的文本。

起初我会得到错误。
“线程 1:exc_bad_instruction(code=exc_i386_invop,subcode=0x0)” 指向某段代码(见代码)但现在我只得到错误 “ fatal error :索引超出范围”

问题出在第一个选择器中,如果我在那里(在模拟器中!)更改任何内容,应用程序就会崩溃。如果我只更改第二个选择器然后更新标签,它会更改为“1 天”或“2 周”,而不仅仅是“天”或“周”。

我的 Storyboard:

main.storyboard

我的代码:

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var PickerView1: UIPickerView!
@IBOutlet weak var PickerView2: UIPickerView!
@IBOutlet weak var outputLabel: UILabel!
@IBAction func changeLabel(_ sender: UIButton) {
    outputLabel.text = outputTotal
}

var list1 = [""]
var list2 = [""]
var output1 = ""
var output2 = ""
var outputTotal = ""

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

// Aangeven welke items er in de pickerview komen
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if (pickerView.tag == 1){
        return "\(list1[row])"
    } else {
        return "\(list2[row])"
    }
}

// Aantal rijen weergeven
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if (pickerView.tag == 1){
        return list1.count
    } else {
        return list2.count
    }
}

// Label veranderen naar input van PickerView1
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    output1 = list1[row]
    output2 = list2[row] // error points here
    outputTotal = output1 + " " + output2
}

override func viewDidLoad() {
    list1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
    list2 = ["days", "weeks"]
    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.
}
}

谁能帮帮我,谢谢!

最佳答案

我想你忘了检测在 pickerView(_:didSelectRow:inComponent:) 中选择了哪个 pickView:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView.tag == 1 {
        output1 = list1[row]
    } else {
        output2 = list2[row]
    }
    outputTotal = output1 + " " + output2
}

关于swift - 线程 1 : exc_bad_instruction(code=exc_i386_invop, 子代码 = 0x0)/ fatal error :索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43183153/

相关文章:

ios - 如何使用和调试不存在模拟器的 iOS 版本?

C++ 等待所有线程完成

ios - 转换实现协议(protocol)的 View Controller

ios - 从现有 NSArray 创建新 NSArray 的标准约定是什么?

ios - SwiftUI - 此代码是否实例化一个新的场景对象?

objective-c - 显示应用的构建日期

python - Python 线程中的死锁

c - FreeRTOS 锁和任务

ios - Swift:更改标签栏的图像色调颜色?

ios - PHImageManager.requestImageForAsset 在为视频创建缩略图时返回 nil