//类里面有一个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
}
Jian Shu saw such an article
Be especially careful when archiving and unarchiving object arrays. For customized objects under iOS
You must pay attention when implementing archiving operations
Only use nsdata as an intermediary to convert specific ideas
归档 customclass ->实现nscoding->NSKeyedArchiver.archivedDataWithRootObject一个实例到nsdata->归档这个nsdata
解档 过程相反NSKeyedUnarchiver.unarchive as nsdata->cutsom=NSKeyedUnarchiver.narchiveObjectWithData->终于拿到
So the code is changed to this
//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
}
Thank you for your answer.
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...