在VC1中回调后保存了数据
代码
func pass(data: [TeamListData]) {
print("ARRAY DATA RECEIVED:\(data)")
participantsData = data
self.collectionView.reloadData()
UserDefaults.standard.setValue( try? PropertyListEncoder().encode(data),forKey: "sessiondata")
}
VC1中的viewDidLoad内部
func storeValidaion(){
// Retrive Array Values
if participantsData == nil {
if let data = UserDefaults.standard.value(forKey:"sessiondata") as? Data {
guard let sessionData = try? PropertyListDecoder().decode(Array<TeamListData>.self,from: data) else {
return
}
print("ARRAY VALUES: \(sessionData)")
self.participantsData = sessionData
self.collectionView.reloadData()
}
}
}
,
您不是在寻找缓存,而是在寻找持久性存储。根据数据的来源和所需的解决方案,可以使用磁盘,UserDefaults或数据库方法,例如CoreData,Realm或其他。
这里有一个方便的教程,其中包含大量代码,用于使用NSCoding将自定义对象存储在UserDefaults中:https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/PersistData.html
例如
符合NSCoding:
struct PropertyKey {
static let name = "name"
static let photo = "photo"
static let rating = "rating"
}
class Meal: NSObject,NSCoding {
let name: String
let photo: UIImage
let rating: Int
required convenience init?(coder aDecoder: NSCoder) {
// The name is required. If we cannot decode a name string,the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
return nil
}
// Because photo is an optional property of Meal,just use conditional cast.
let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
let rating = aDecoder.decodeInteger(forKey: PropertyKey.rating)
// Must call designated initializer.
self.init(name: name,photo: photo,rating: rating)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name,forKey: PropertyKey.name)
aCoder.encode(photo,forKey: PropertyKey.photo)
aCoder.encode(rating,forKey: PropertyKey.rating)
}
}
保存数据:
private func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals,toFile: Meal.ArchiveURL.path)
if isSuccessfulSave {
os_log("Meals successfully saved.",log: OSLog.default,type: .debug)
} else {
os_log("Failed to save meals...",type: .error)
}
}
加载数据:
private func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal]
}
另一方面,Realm提供了很大的灵活性,可以花更多的时间来学习第三方库:https://realm.io/docs/swift/latest/#models
本文链接:https://www.f2er.com/3146672.html