gpt4 book ai didi

arrays - 如何在swift代码中保存一组类

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:52 25 4
gpt4 key购买 nike

我正在尝试保存一组类,这是我目前的代码:

数组:

var person1 = person(name: "Bob", age: 22)
var person2 = person(name: "John", age: 10)
var array = [person1, person2]

自定义类:

import UIKit

class person: NSObject, NSCoding {

var name : String
var age : Int

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

required init (coder aDecoder: NSCoder) {
name = (aDecoder.decodeObject(forKey: "name") as? String)!
age = (aDecoder.decodeObject(forKey: "age") as? Int)!
}

func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
}
}

保存数组:

let SavedData = NSKeyedArchiver.archivedData(withRootObject: array)

let defaults = UserDefaults.standard

defaults.set(SavedData, forKey: "myPeople")

加载数组:

let saveddata = UserDefaults.standard.object(forKey: "myPeople") as? Data

if saveddata != nil{
array = (NSKeyedUnarchiver.unarchiveObject(with: saveddata!) as? [person])!
}

错误在 age = (aDecoder.decodeObject(forKey: "age") as? Int)!

这行

Unknown class iewripple in Interface Builder file.

最佳答案

发生错误是因为您正在编码一个 Int 但解码一个失败的 object

有一个专用方法decodeInteger(forKey

请遵循类名以大写字母开头,变量名以小写字母开头的命名约定。

class Person: NSObject, NSCoding {

要解决此问题,请将 init(coder 方法更改为

required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
age = aDecoder.decodeInteger(forKey: "age")
}

强制展开字符串是 100% 安全的,因为该值始终被编码为非可选值。


保存数组

let savedData = NSKeyedArchiver.archivedData(withRootObject: array)
UserDefaults.standard.set(savedData, forKey: "myPeople")

加载数组

if let savedData = UserDefaults.standard.object(forKey: "myPeople") as? Data {
array = NSKeyedUnarchiver.unarchiveObject(with: savedData) as! [Person]
}

如果可选绑定(bind) as?数据成功。

关于arrays - 如何在swift代码中保存一组类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45012834/

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