首页 > 解决方案 > Swift 4,使用 Array 和 TableViewCell 存储和显示数据

问题描述

我正在制作一个应用程序,允许用户保持用户名和密码的顺序。目前,当用户退出应用程序时,我遇到了问题,数据或 TableViewCell 未存储或显示。我正在使用一个数组。

我假设是因为之后没有存储数据。CoreData 或 UserDefaults 是一个简单的解决方案吗?我想避免使用 Firebase。

有人可以解释或展示如何在代码中实现 CoreData/UserDefaults 吗?我进行了很多搜索,但我发现很难理解如何在我的代码中应用它,尤其是数组和 TableViewCell。非常感谢您的帮助。

图片如下。

这是我的代码:

主视图控制器:

class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView:UITableView?


override func viewDidLoad() {
    super.viewDidLoad()


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InformasjonTableViewCell") as! InformasjonTableViewCell

    let informasjon:Informasjon = informasjoner[indexPath.row];

    if(informasjon.image != nil){
        cell.imageViewInfo?.image = informasjon.image
    } else {
        cell.imageViewInfo?.image = UIImage(named: informasjon.imageName!)
    }

    cell.epostLabel?.text = informasjon.labelEpost
    cell.passordLabel?.text = informasjon.labelPassord
    cell.applikasjonLabel?.text = informasjon.labelApplikasjon

    return cell
}

// EDIT / UPDATE CELL

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let informasjon = informasjoner[indexPath.row]

    let deleteAction = UITableViewRowAction(style: .default, title: "Delete"){
        (action, indexPath) in
        self.deleteAction(informasjon: informasjon, indexPath: indexPath)
    }
        //call delete action
    deleteAction.backgroundColor = .red;
    return [deleteAction]
    }
private func deleteAction(informasjon: Informasjon, indexPath: IndexPath){
let alert = UIAlertController(title: "Delete",
                              message: "Are u sure?",
                              preferredStyle: .alert)

    let deleteAction = UIAlertAction(title: "Yes",
                                     style: .default){ (action) in
        informasjoner.remove(at: indexPath.row)
        self.tableView?.deleteRows(at: [indexPath], with: .automatic)

    }
    let cancelAction = UIAlertAction(title: "No",
                                     style: .default,
                                     handler: nil);
    alert.addAction(deleteAction);
    alert.addAction(cancelAction);
    present(alert, animated: true);

}
}

信息表视图单元:

 import UIKit

 class InformasjonTableViewCell: UITableViewCell {


@IBOutlet weak var imageViewInfo: UIImageView?
@IBOutlet weak var epostLabel: UILabel?
@IBOutlet weak var passordLabel: UILabel?
@IBOutlet weak var applikasjonLabel: UILabel!




override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)


}

}

添加信息VC:

import UIKit

class AddInfoVC: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet weak var txtEpost:UITextField?
@IBOutlet weak var ImageInfo:UIImageView?
@IBOutlet weak var txtPassord:UITextField?
@IBOutlet weak var txtApplikasjon: UITextField!


var newInfo = Informasjon()

@IBAction func btnSave(sender:UIButton){
print("Press Save!")
    if(newInfo.image == nil || newInfo.labelEpost?.count == 0 || newInfo.labelPassord?.count == 0 || newInfo.labelApplikasjon?.count == 0){
        let alertController = UIAlertController(title: "Alert", message: "Please set", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default){
            (action) in
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil);

    } else{
        informasjoner.append(newInfo);
        navigationController?.popViewController(animated: true)
        let mainViewController = self.navigationController?.topViewController as? MainViewController
        mainViewController?.tableView?.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    //Tap to ImageView
    let tapGestureToImageView = UITapGestureRecognizer(target: self, action: #selector(tapToImageView(sender:)))
    tapGestureToImageView.numberOfTapsRequired = 1
    ImageInfo?.isUserInteractionEnabled = true;
    ImageInfo?.addGestureRecognizer(tapGestureToImageView);

    self.txtEpost?.delegate = self;
    self.txtPassord?.delegate = self;
    self.txtApplikasjon?.delegate = self;


}

楷模

信息.swift:

import Foundation
import UIKit

class Informasjon {
var imageName: String?
var image: UIImage?
var labelEpost: String?
var labelPassord: String?
var labelApplikasjon: String?
convenience init(imageName:String, labelEpost:String, labelPassord:String,labelApplikasjon:String ) {
    self.init()
    self.imageName = imageName
    self.labelEpost = labelEpost
    self.labelPassord = labelPassord
    self.labelApplikasjon = labelApplikasjon
}
}

图片 1 -> 应用程序从情节提要中的外观。

图 2 -> 应用程序在模拟器中的外观。

标签: iosuitableviewcore-dataswift4userdefaults

解决方案


你应该只使用 NSUserDefaults 来存储首选项——只是你的应用程序功能的首选项,没有别的。像用户数据这样的其他任何东西都应该存储在其他地方。特别是如果说这是敏感的,并且您不想冒用户数据的风险,因为 plist 文件直接在应用程序目录中可用。

使用 UserDefaults 存储应用程序数据的另一个缺点是所有数据都将存储为属性列表文件。整个文件是作为一个整体读入和写出的,因此如果您使用 UserDefaults 存储大量仅部分更改的数据,您将浪费大量时间进行不必要的 I/O。

相反,CoreData/Realm 始终是持久化应用数据的更好选择。

要了解如何在 CoreData 中存储 -

要了解如何在 Realm 中存储 -


推荐阅读