Best practice for storing temporary data in swift

前端 未结 5 1190
太阳男子
太阳男子 2021-01-02 18:56

I have developed an app that gets a lot of JSON data from server and shows on different VCs.What I did was getting data and setting data to static v

5条回答
  •  一个人的身影
    2021-01-02 19:17

    You should not store data to UserDefaults, user defaults is just a key value based file which is mostly used to store some data about user, for example :

    doNotShowAdds : true
    isUserLogedIn :true.
    

    You should not use keychain either since keychain is encrypted container where u store critic data about user, for example : password.

    You don't need to use database

    My opinion is that you should not use global variables, mainly I try to make viewController data specific for itself, the data should not be accessed from anywhere in your project. When to use global variables in Swift

    Mostly I make service protocols with implementations for specific view controllers. Anyways, each controller should have its own part of data for example

    class MyViewControllerOne {
        private var data :Array;
    }
    
    class MyViewControllerTwo {
        private var data :Array;
    }
    

    Once you load data from your API, the data will be there, until you close your app.

    You can always make another class which will contain this data and maybe predicates for cleaner approach for example :

    protocol MyViewControllerOneService {
        func search() -> Array;
    }
    
    class MyViewControllerOneServiceImpl :MyViewControllerService {
    public var data :Array;
    
    public func search(searchString :String) -> Array{
        let predicate = NSPredicate() ...
        let filteredArray = self.data.filter { evaluate...}
        return filteredArray;
        }
    }
    

    I use similar approach, instead of saving data in my service classes (business logic), I got repositories which I use to get data from database. Since you don't have any database this approach is okay.

    and then instead of

    class MyViewControllerOne {
        private var data :Array;
    }
    

    you can use

    class MyViewController {
        private var myViewControllerService :MyViewControllerOneServiceImpl;
    }
    

    Hope it helps, Best regards!

提交回复
热议问题