如果你項(xiàng)目里面的歸檔用大量的屬性瓷叫,沒(méi)次增加新的屬性時(shí) 還需要在歸檔和解檔的方法里寫(xiě)重復(fù)的代碼谎砾,看著重復(fù)的代碼就特別惡心樟插!……怎么辦呢韵洋? -- 如果在歸檔和解檔里面用運(yùn)行時(shí),這個(gè)辦法就辦啦黄锤, 想要看源碼demo只需要點(diǎn)擊 github 廢話不多說(shuō)直接上代碼
1. 自定義屬性
var name :String?
var address :String?
var professional:String?
var age :Int = 0
2.歸檔
internal func encodeWithCoder(aCoder: NSCoder){
var count :UInt32 = 0
let ivar = class_copyIvarList(Person.self, &count)
for i in 0..<Int(count) {
let iv = ivar[i]
//獲取成員變量的名稱 -》 c語(yǔ)言字符串
let cName = ivar_getName(iv)
//轉(zhuǎn)換成String字符串
guard let Strname = String(UTF8String: cName) else{
//繼續(xù)下一次遍歷
continue
}
//利用kvc 取值
let value = self.valueForKey(Strname)
aCoder.encodeObject(value, forKey: Strname)
// print(value)
}
// 釋放c 語(yǔ)言對(duì)象
free(ivar)
}
3.解檔
internal required init?(coder aDecoder: NSCoder){
super.init()
var count :UInt32 = 0
let ivar = class_copyIvarList(Person.self, &count)
for i in 0..<Int(count) {
let iv = ivar[i]
//獲取成員變量的名稱 -》 c語(yǔ)言字符串
let cName = ivar_getName(iv)
//轉(zhuǎn)換成String字符串
guard let Strname = String(UTF8String: cName) else{
//繼續(xù)下一次遍歷
continue
}
//進(jìn)行解檔取值
let value = aDecoder.decodeObjectForKey(Strname)
//利用kvc給屬性賦值
setValue(value, forKeyPath: Strname)
// print(value)
}
// 釋放c 語(yǔ)言對(duì)象
free(ivar)
搪缨、