注意:
運行時
是OC
的,其實Swift``官方
并不是太提倡
, 需要在class
前加上@objcMembers
聲明該對象是OC
的,不然獲取不了對象屬性列表
使用
import UIKit
class ViewController: UIViewController {
let p = UserInfo()
override func viewDidLoad() {
super.viewDidLoad()
p.name = "yusong"
p.age = 20
// p.professional = "ios"
p.address = "jiaotukeji"
}
// MARK: - 歸檔
@IBAction func archiveclick(_ sender: Any) {
UserTool.saveUser(p)
}
// MARK: - 解檔
@IBAction func solutionFileClick(_ sender: Any) {
let p = UserTool.getUser()
guard let user = p else{
print("文件不存在")
return
}
print(user.name,user.address ,user.age ,user.professional)
}
// MARK: - 刪檔
@IBAction func removeClick(_ sender: Any) {
UserTool.removeUser()
}
}
實現(xiàn)
import UIKit
@objcMembers class UserInfo: NSObject,NSCoding {
// MARK: - 屬性
var name :String?
var address :String?
var professional:String = "123" // 給定初始值
var age :Int = 0
// MARK: - 初始方法
override init() {
super.init()
}
// MARK: - 歸檔
func encode(with aCoder: NSCoder) {
for Strname in getAllPropertys() {
let value = self.value(forKey: Strname)
aCoder.encode(value, forKey: Strname)
}
}
// MARK: - 解檔
internal required init?(coder aDecoder: NSCoder){
super.init()
for Strname in getAllPropertys() {
let value = aDecoder.decodeObject(forKey: Strname)
//利用kvc給屬性賦值
setValue(value, forKeyPath: Strname)
}
}
// MARK: - 獲取屬性數(shù)組
func getAllPropertys()->[String]{
// 這個類型可以使用CUnsignedInt,對應Swift中的UInt32
var count: UInt32 = 0
let properties = class_copyPropertyList(self.classForCoder, &count)
var propertyNames: [String] = []
// Swift中類型是嚴格檢查的执隧,必須轉換成同一類型
for i in 0..<Int(count) {
// UnsafeMutablePointer<objc_property_t>是可變指針,因此properties就是類似數(shù)組一樣,可以通過下標獲取
let property = properties![i]
let name = property_getName(property)
// 這里還得轉換成字符串
let strName = String(cString: name)
propertyNames.append(strName);
}
// 不要忘記釋放內(nèi)存僧须,否則C語言的指針很容易成野指針的
free(properties)
return propertyNames;
}
// MARK: - 獲取對應屬性的值 沒有側返回nil
func getValueOfProperty(property:String)->AnyObject?{
let allPropertys = self.getAllPropertys()
if(allPropertys.contains(property)){
return self.value(forKey: property) as AnyObject
}else{
return nil
}
}
}
class UserTool{
// MARK: - 歸檔路徑設置
static private var Path: String{
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
return (path as NSString).appendingPathComponent("account.plist")
}
/// 存檔
static func saveUser(_ user: NSObject){
NSKeyedArchiver.archiveRootObject(user, toFile: Path)
}
/// 獲取歸檔模型
static func getUser()-> UserInfo? {
let user = NSKeyedUnarchiver.unarchiveObject(withFile: Path) as? UserInfo
return user
}
/// 刪除歸檔
static func removeUser() {
if FileManager.default.fileExists(atPath: Path){
try! FileManager.default.removeItem(atPath: Path) // 刪除文件
}else{
}
}
}