swift - 我在尝试将数据设置为 Struct 时做错了什么

标签 swift struct

我正在尝试创建一个能够在屏幕之间传递数据的结构。但是,当我将数据设置为我的 Struct 属性然后尝试在另一个屏幕中使用它时,我得到的值为“nil”。我究竟做错了什么?

对象结构:

import UIKit

struct Objetos {
    var nome: String
    var foto: UIImage
}

这就是我尝试设置值的方式:

var objeto = Objeto(nome: "", foto: UIImage())

@IBAction func botaoAdcItem(_ sender: UIButton) {
    if (self.namePreview!.text != nil) && (self.imagePreview!.image != nil) {
       objeto?.nome = self.namePreview.text!
       objeto?.foto = self.imagePreview.image!

       self.navigationController?.popViewController(animated: true)
    }
    else { return }
}

这就是我尝试读取数据的方式:

class ViewController: UIViewController, CLLocationManagerDelegate,  UITableViewDataSource {
     @IBOutlet weak var itensTableView: UITableView!
     var arrayNomes = NSMutableArray()

     var objeto: Objetos?
     var objetos = [Objetos]()

        //TableView
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

          for nome in objetos {
              arrayNomes.add(nome)
          }
          return arrayNomes.count //Nil value
     }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

          let cell = itensTableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! tableviewCell
          cell.nameCell.text = objeto?.nome //Nil value                    
          cell.imageViewCell.image = objeto?.foto //Nil value
          return cell
     }

     override func viewDidAppear(_ animated: Bool) {
          self.itensTableView.reloadData()
     }

Storyboard:

enter image description here

最佳答案

在你的第二个代码片段中,你从未将 objetos 初始化为任何东西。因此,当您尝试在 objetos 上设置其中一个属性时,没有任何反应,因为 objetos 不存在。

解决方案:在尝试使用之前初始化objetos

关于swift - 我在尝试将数据设置为 Struct 时做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51218814/

相关文章:

c++ - 将文件读入结构 (C++)

c++ - C/C++ 中结构的 `new` 和 `new()` 有什么区别?

c++ - 结构中的结构,初始化

在 C 中调用结构体

swift - const unsigned char ptr (UnsafePointer<CUnsignedChar>) 到 String

swift - 我的 Swift UI 中的 TextField 对点击和点击没有响应,无法输入文本,代码是否有问题?

Swift UIColor 扩展最佳实践

python - 如何从Python中的二进制文件解析序列化的C结构?

ios - 将 JWTDecode 添加到现有的 iOS 项目,找不到框架

ios - 每次呈现时查看 Controller 原点更改