iOS12解归档
2023-04-18 本文已影响0人
東玖零
背景:随着H5的发展,老板们认为跨平台的H5可以降低人力成本 ,客户端需求基本都被H5承接,原生就有时间做优化工作,我们发现有很多App系统需要iOS12及以上了,例如大家熟知大型聊天软件。我们也紧跟时代尾巴把最低版本设置为iOS12,就发现了如下警告:
1、'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: instead
2、'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead
经过查询各种资料简单封装了一个tools结构体,代码如下
struct Tools {
// iOS 12以上方法
@discardableResult
static func saveObject(_ obj:Any?, forKey key:String) -> Bool {
if key == "" {
return false
}
let userDefalut = UserDefaults.standard
guard let ob = obj else {
userDefalut.removeObject(forKey: key)
return userDefalut.synchronize()
}
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: ob, requiringSecureCoding: false)
userDefalut.set(data, forKey: key)
return userDefalut.synchronize()
} catch let err {
DLog("文件缓存失败", err)
return false
}
}
// iOS 12以上方法
@discardableResult
static func object(forKey key:String, ofClass:[AnyClass]) -> AnyObject? {
if key == "" {
return nil
}
let userDefalut = UserDefaults.standard
if let data = userDefalut.object(forKey: key) as? Data {
do {
return try NSKeyedUnarchiver.unarchivedObject(ofClasses: ofClass, from: data) as AnyObject
} catch let err {
DLog("读取文件缓存失败", err)
}
}
return nil
}
}
首先们要准备一个商品类,稍后对他解归档
// 商品基类
class ProductModel: NSObject, NSCoding, NSSecureCoding {
var productId = "" // 商品id
var productName = "" // 短名
override init() {
super.init()
}
// 必须实现的NSCoding协议方法
func encode(with aCoder: NSCoder) {
aCoder.encode(productId, forKey: "productId")
aCoder.encode(productName, forKey: "productName")
}
// 必须实现的NSCoding协议方法
required init?(coder aDecoder: NSCoder) {
super.init()
productId = aDecoder.decodeString("productId")
productName = aDecoder.decodeString("productName")
}
static var supportsSecureCoding: Bool {
return true
}
}
我们写了测试代码如下:
{
var list = [ProductModel]()
let p = ProductModel()
p.productId = "test00001"
list.append(p)
Tools.saveObject(list, forKey: "key")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
var classList:[AnyClass] = []
classList.append(NSArray.self)
classList.append(ProductModel.self)
classList.append(NSString.self)
let productList = Tools.getObject1(forKey: "key", ofClass: classList) as? [ProductModel]
DLog("------>>>>>",productList ?? "productList is nil")
})
}
NSSecureCoding 这个协议必须实现,不然解档失败,失败信息如下:
["读取文件缓存失败", Error Domain=NSCocoaErrorDomain Code=4864 "This decoder will only decode classes that adopt NSSecureCoding. Class 'Demo.ProductModel' does not adopt it." UserInfo={NSDebugDescription=This decoder will only decode classes that adopt NSSecureCoding. Class 'Demo.ProductModel' does not adopt it.}]
classList.append(NSString.self)这一句必须添加,不然也会报一堆警告,打印信息如下:
2023-04-19 14:13:59.931486+0800 Demo[14059:155507] [general] *** -[NSKeyedUnarchiver validateAllowedClass:forKey:] allowed unarchiving safe plist type ''NSString' (0x7ff863b906b0) [/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework]' for key 'productId', even though it was not explicitly included in the client allowed classes set: '{(
"'NSArray' (0x7ff863b7b800) [/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework]",
"'Demo.ProductModel' (0x104c46360) [/Users/adong/Library/Developer/CoreSimulator/Devices/10E1F45C-50C7-49EB-8750-712778B52F58/data/Containers/Bundle/Application/BA1413BF-8D6F-4B13-8E8F-ABBFF57C5AAE/Demo.app]"
)}'. This will be disallowed in the future.