如何在应用程序关闭并使用Swift打开后如何维护UICollectionView数据缓存?

问题描述 投票:0回答:1

在我的情况下,我正在尝试维护cacheUICollectionView数据。在这里,VC2VC1我正在传递数组数据,VC1我正在传递传递的数据到UICollectionView中。现在,如果我关闭并重新打开应用程序,则无法看到UICollectionView数据已全部删除,但我必须维护缓存。怎么做?

[从VC2传递的数组中收集视图数据加载

 func pass(data: [TeamListData]) {
        print("ARRAY DATA RECEIVED:\(data)")
        participantsData = data
        self.collectionView.reloadData()
    }

我的数组数据

ARRAY DATA RECEIVED:[TeamListData(userid: Optional("1"), firstname: Optional(“abc”), designation: Optional("Analyst"), profileimage: Optional(“url.jpg"), isSelected: true), TeamListData(userid: Optional(“2”), firstname: Optional(“def”), designation: Optional("Executive"), profileimage: Optional(“url.jpg"), isSelected: true)]
ios swift uicollectionview
1个回答
0
投票

在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()
            }
        }

    }

0
投票

您不是在寻找缓存,而是在寻找永久性存储。根据数据的来源以及所需的解决方案,可以使用磁盘,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...", log: OSLog.default, type: .error)
    }
}

正在加载数据:

private func loadMeals() -> [Meal]?  {
    return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal]
}

另一方面,Realm提供了很大的灵活性,可以花更多的时间来学习第三方库:https://realm.io/docs/swift/latest/#models

© www.soinside.com 2019 - 2024. All rights reserved.