gpt4 book ai didi

ios - 使用 Codable 与 Swift 归档

转载 作者:行者123 更新时间:2023-11-28 13:53:57 26 4
gpt4 key购买 nike

我正在尝试使用 codable 在 iOS 应用程序中快速保存来自 textFields 的一些数据,但是当我定义用于归档的函数时,xcode 告诉我“无法推断通用参数‘值’”。

我正在学习归档,如果有人能帮助我,我将非常感激。

这是我正在使用的代码

class ProfileViewController: UITableViewController {
var currentProfile: Profile?
@IBOutlet weak var name: UITextField!
@IBOutlet weak var surname: UITextField!

@IBAction func saveProfileButton(_ sender: Any) {
addCurrentProfile()
saveProfile()
}

func addCurrentProfile(){
currentProfile?.name = name.text ?? ""
currentProfile?.surname = surname.text ?? ""
}

struct Profile {
var name: String
var surname: String

enum CodingKeys: String, CodingKey {
case name
case surname

}

init(name:String, surname:String) {
self.name = name
self.surname = surname
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(surname, forKey: .surname)

}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
surname = try container.decode(String.self, forKey: .surname)
}
}

func saveProfile() {
do {
let data = try PropertyListEncoder().encode(currentProfile)
let success = NSKeyedArchiver.archiveRootObject(data, toFile: profile_data.path)
print(success ? "Successful save" : "Save Failed")
} catch {
print("Save Failed")
}
}
}

最佳答案

首先是让你的结构确认 Codable 协议(protocol),例如:

struct Profile:Codable {
var name: String
var surname: String

enum CodingKeys: String, CodingKey {
case name
case surname

}

init(name:String, surname:String) {
self.name = name
self.surname = surname
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(surname, forKey: .surname)

}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
surname = try container.decode(String.self, forKey: .surname)
}
}

然后,您可以使用 PropertyListEncoder 实现对象,如下所示:

func saveProfile() {
do {
let data = try PropertyListEncoder().encode(currentProfile)
let success = NSKeyedArchiver.archiveRootObject(data, toFile: profile_data.path)
print(success ? "Successful save" : "Save Failed")
} catch {
print("Save Failed")
}
}

关于ios - 使用 Codable 与 Swift 归档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com