简体   繁体   English

试图将int从文本字段转换为数组swift 4

[英]Trying to convert an int from a textfield to an array swift 4

I am developing an iOS app, I am trying to use a textfield and a button to submit an integer into an array so that I can store it using 'userdefaults'. 我正在开发一个iOS应用程序,试图使用文本字段和按钮将整数提交到数组中,以便可以使用“ userdefaults”将其存储。 So far I have got a different textfield adding the String entered into the array and storing it in the user defaults. 到目前为止,我有一个不同的文本字段,将输入的String添加到数组中并将其存储在用户默认值中。

     @IBAction func workBtn(_ sender: Any)
{
    let kidnum: Int = Int(enteredScore.text!)!
    kidName.append(enteredName.text!)
    kidScore.append(kidnum)

    enteredName.text?.removeAll()
    enteredScore.text?.removeAll()
}


@IBAction func finishBtn(_ sender: Any)
{
    let userDefaults = UserDefaults.standard
    userDefaults.set(kidName, forKey: "Pupil Name")
    userDefaults.set(kidScore, forKey: "Pupil Score")

    userDefaults.synchronize()
}

workBtn is the add button I am using, I did also try to use a string as I don't actually need the integer for working out but just to display a score but I could not get it to save, I am passing it through it to be displayed on a table view controller cell. workBtn是我正在使用的添加按钮,我也尝试使用字符串,因为我实际上并不需要整数来计算,而只是显示一个分数,但我无法保存它,我正在通过它显示在表格视图控制器单元上。 Thanks 谢谢

I am using Xcode 9.1 Swift 4, Thanks. 我正在使用Xcode 9.1 Swift 4,谢谢。

Edit*** After running it I got an error in this function on the line marked stating "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" 编辑***运行它后,在标有“线程1:致命错误:解开可选值时意外发现nil”的行上,此函数出现错误

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let userDefaults = UserDefaults.standard
    var nameArray: [String] = userDefaults.object(forKey:"Pupil Name") as! [String]
    //Error occurring on next line.
    var scoreArray: [Int] = userDefaults.object(forKey: "Pupil Score") as! [Int]

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "\(nameArray[indexPath.item]) -Score: \(scoreArray[indexPath.item])"

    userDefaults.synchronize()

    return cell
}

The error you are receiving means you are accessing a nil value somewhere where you don't expect it. 您收到的错误意味着您正在某个意外的地方访问nil值。 This is most likely by force-unwrapping some value which you do constantly in your code. 这很可能是通过强制展开一些在代码中不断执行的值来实现的。 Try avoiding the usage of ! 尝试避免使用! . In your code it might be any of lines such as let kidnum: Int = Int(enteredScore.text!)! 在您的代码中,可能是let kidnum: Int = Int(enteredScore.text!)!类的任何行let kidnum: Int = Int(enteredScore.text!)! but it might also be some field is missing connection for instance and is declared as @IBOutlet weak var enteredName: UITextField! 但也可能是某些字段缺少连接,例如,它声明为@IBOutlet weak var enteredName: UITextField! which unfortunately is a default. 不幸的是,这是默认设置。

To debug this you might want to enable exception breakpoint: In navigator on your left side of Xcode on the top there is an icon for breakpoints (a bullet). 要调试此功能,您可能需要启用异常断点:在Xcode左侧顶部的导航器中,有一个断点图标(项目符号)。 Select it and then check on the bottom left and find a "+" button, press it and select "Exception breakpoint...". 选择它,然后在左下方检查并找到一个“ +”按钮,按下它并选择“ Exception breakpoint ...”。 Then simply click away. 然后,只需单击即可。 Now your execution will stop whenever an exception like yours is hit. 现在,只要遇到像您这样的异常,您的执行就会停止。 Run your project and find the line, object that is nil and should not be. 运行您的项目,找到行,对象为nil,不应为n。 Then fix your issue. 然后解决您的问题。

But in general try writing your code more like the following: 但通常,尝试编写代码的方式如下:

    @IBOutlet private weak var scoreTextField: UITextField?
    @IBOutlet private weak var nameTextField: UITextField?

    private typealias NameScore = (name: String, score: Int)
    private var dataArray: [NameScore] = [NameScore]()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
    }

    @IBAction private func workPressed() {
        let scoreValue: Int? = {
            guard let string = scoreTextField?.text, let integer = Int(string) else {
                return nil
            }
            return integer
        }()

        guard let score = scoreValue else {
            print("Could not parse integer value") // TODO: Show alert view
            return
        }

        guard let name = nameTextField?.text else {
            print("Name was not provided") // TODO: Show alert view
            return
        }

        dataArray.append((name: name, score: score))

        // Clear text fields
        scoreTextField?.text = nil
        nameTextField?.text = nil
    }


    @IBAction private func finishPressed() {
        saveData()
    }

    private let pupilNameKey: String = "name"
    private let pupilScoreKey: String = "score"
    private let pupilDataKey: String = "pupil_data"

    private func saveData() {
        // Let's convert data into something that makes more sense for safety
        let dataToSave: [[String: Any]] = dataArray.map { object in
            return [pupilNameKey: object.name,
                    pupilScoreKey: object.score]
        }

        UserDefaults.standard.set(dataToSave, forKey: pupilDataKey)
        UserDefaults.standard.synchronize()
    }

    private func loadData() {
        guard let savedData = UserDefaults.standard.value(forKey: pupilDataKey) as? [[String: Any]] else {
            // No saved data or incorrect format
            return
        }

        dataArray = savedData.flatMap { descriptor in
            guard let name = descriptor[pupilNameKey] as? String, let score = descriptor[pupilScoreKey] as? Int else {
                return nil // Could not parse this object
            }
            return (name: name, score: score)
        }
    }

And table view: 和表视图:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let dataObject = dataArray[indexPath.row]
        cell.textLabel?.text = "\(dataObject.name) -Score: \(dataObject.score)"
        return cell
    }

I hope the code speaks for itself on how to avoid force unwrapping and also how to pack your data. 我希望代码能说明如何避免强制展开以及如何打包数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM