使用 UserDefaults 保存 TableView 单元格

发布于 2025-01-10 02:17:26 字数 1627 浏览 2 评论 0原文

我正在尝试使用 UserDefaults 获取 tableView 的单元格,但在我重新加载应用程序后,它始终为空

这是我的模型:

struct Note: Codable {
    var title: String
    var description: String
}

class Notes {
    var stock: [Note] = []
}

视图控制器

var model = Notes()

这是我获取数据的方式

override func viewDidLoad() {
        super.viewDidLoad()

self.tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
        tableView.reloadData()

if let fetchedData = UserDefaults.standard.data(forKey: "notes") {
            let fetchedBookies = try! PropertyListDecoder().decode([Note].self, from: fetchedData)
            print(fetchedBookies)
        } else {
            model.stock = []
        }
}

这是我的单元格


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.titleOutlet.text = self.model.stock[indexPath.row].title
        cell.descriptionOutlet?.text = self.model.stock[indexPath.row].description
        return cell
    }

我如何保存数据

@IBAction func check(_ sender: Any) {
        let newstock = Note(title: "check", description: "check2")
        model.stock.append(newstock)
        print(model.stock.count)
        
        
        let bookiesData = try! PropertyListEncoder().encode(model.stock)
        UserDefaults.standard.set(bookiesData, forKey: "notes")

        tableView.reloadData()
    }

非常感谢!

I'm trying to get cell of tableView using UserDefaults, but after i reload app it is always empty

This is my Model:

struct Note: Codable {
    var title: String
    var description: String
}

class Notes {
    var stock: [Note] = []
}

View contoller

var model = Notes()

This is how i get data

override func viewDidLoad() {
        super.viewDidLoad()

self.tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
        tableView.reloadData()

if let fetchedData = UserDefaults.standard.data(forKey: "notes") {
            let fetchedBookies = try! PropertyListDecoder().decode([Note].self, from: fetchedData)
            print(fetchedBookies)
        } else {
            model.stock = []
        }
}

This is my cell


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.titleOutlet.text = self.model.stock[indexPath.row].title
        cell.descriptionOutlet?.text = self.model.stock[indexPath.row].description
        return cell
    }

How i save data

@IBAction func check(_ sender: Any) {
        let newstock = Note(title: "check", description: "check2")
        model.stock.append(newstock)
        print(model.stock.count)
        
        
        let bookiesData = try! PropertyListEncoder().encode(model.stock)
        UserDefaults.standard.set(bookiesData, forKey: "notes")

        tableView.reloadData()
    }

Thank you very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等待我真够勒 2025-01-17 02:17:26

我建议您使用 Json 编码器/解码器。

首先设置您的 Notes 类以符合 Codable:

class Notes: Codable {
    var stock: [Note] = []
}

这是如何使用 Json 编码器/解码器的示例:

func save(notes: Notes) throws {
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(notes)
        UserDefaults.standard.set(data, forKey: "notes")
    } catch let error {
        throw error
    }
}

func load() -> Notes {
    guard let data = UserDefaults.standard.data(forKey: "notes") else {
        return Notes() // Default
    }
    let decoder = JSONDecoder()
    do {
        let object = try decoder.decode(Notes.self, from: data)
        return object
    } catch {
        return Notes() // Default
    }
}

在您的代码中,只需调用 load() 即可从中获取笔记用户默认值

save(notes:) 将它们保存到用户默认值中。

I recommend you to use Json Encoder/Deocder.

First set your Notes class to conform to Codable:

class Notes: Codable {
    var stock: [Note] = []
}

Here is an example of how to use Json Encoder / Decoder:

func save(notes: Notes) throws {
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(notes)
        UserDefaults.standard.set(data, forKey: "notes")
    } catch let error {
        throw error
    }
}

func load() -> Notes {
    guard let data = UserDefaults.standard.data(forKey: "notes") else {
        return Notes() // Default
    }
    let decoder = JSONDecoder()
    do {
        let object = try decoder.decode(Notes.self, from: data)
        return object
    } catch {
        return Notes() // Default
    }
}

In your code just call load() to get your notes from User Defaults

And save(notes:) to save them into User Defaults.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文