Heim > Fragen und Antworten > Hauptteil
//类里面有一个dogs的对象数组
class dogHouse: NSObject , NSCoding{
var dogs:[dog]?
required init(coder aDecoder: NSCoder)
{
dogs = aDecoder.decodeObject(forKey: "dogs") as? [dog]
super.init()
}
func encode(with aCoder: NSCoder) {
if dogs != nil{
aCoder.encode(dogs, forKey: "dogs")
}
}
class dog: NSObject , NSCoding {
//名字属性
var name : String?
required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String?
super.init()
}
func encode(with aCoder: NSCoder) {
if name != nil{
aCoder.encode(name, forKey: "name")
}
}
}
//下面是规解档的操作
//MARK: - 规解
func saveModel() -> Bool{
return NSKeyedArchiver.archiveRootObject(self, toFile: ICModelPath)
}
//总是会报错不知道是为什么?
//reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (_TtCC11ArchiveTest8dogHouse3dog) for key (NS.objects); the class may be defined in source code or a library that is not linked'
//MARK: - 解档
class func loadArchiver() -> [dog]?{
let obj = NSKeyedUnarchiver.unarchiveObject(withFile: ICModelPath) as? dogHouse
if obj != nil{
return obj?.dogs
}
return nil
}
简书看到这么一篇文章
在使用对对象数组归档解档 要特别小心 iOS 下对于自定义的对象
要实现归档操作必须注意
只有使用nsdata作为中间者转换具体思路
归档 customclass ->实现nscoding->NSKeyedArchiver.archivedDataWithRootObject一个实例到nsdata->归档这个nsdata
解档 过程相反NSKeyedUnarchiver.unarchive as nsdata->cutsom=NSKeyedUnarchiver.narchiveObjectWithData->终于拿到
所以代码改成这样
//MARK: - 规档
func saveModel() -> Bool{
let data = NSKeyedArchiver.archivedData(withRootObject: self)
return NSKeyedArchiver.archiveRootObject(data, toFile: ICModelPath)
}
//MARK: - 解档
class func loadArchiver() -> [dog]?{
let arch = NSData.init(contentsOf: URL(fileURLWithPath: ICModelPath))
print(arch)
if let data = arch {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
if let temp = unarchiver.decodeObject() as? dogHouse{
print(temp)
return temp.dogs
}
}
//一直解档不出来数据,断点一直断在这里了
return nil
}
谢谢回答。