user6760281
user6760281

Reputation:

can UserDefaults continue save new data after each .synchronize()?

I wrote an app includes a main program A and an action extension B.

Users can use action extension B to save some data into UserDefaults. like this:

let defaults = UserDefaults(suiteName: "group.com.ZeKai")
    defaults?.set(self.doubanID, forKey: "doubanID")
    defaults?.set(self.doubanRating, forKey: "doubanRating")
    defaults?.set(self.imdbRating, forKey: "imdbRating")
    defaults?.set(self.rottenTomatoesRating, forKey: "rottenTomatoesRating")
    defaults?.set(self.chineseTitle, forKey: "chineseTitle")
    defaults?.set(self.originalTitle, forKey: "originalTitle")
    defaults?.synchronize()

Wating to transfer this data to main program A while A is opened.

But if I use action extension twice to save data like data1 and data2, then I open the main program A, only data2 is received by A, means always new data overwrite the new data in UserDefaults.

so, I would like to know whether I can save multiple data in UserDefaults, and they will be all transferred to main program A?

Thanks in advance...

Upvotes: 1

Views: 243

Answers (1)

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

To save multiple data to UserDefaults you should use unique keys for that data. Also read about synchronization:

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

If the data is descriptive as in case you describe. Try to use structures to represent models.

Example of the user struct:

public struct User {

    public var name: String

    init(name: String) {
        self.name = name
    }

    public init(dictionary: Dictionary<String, AnyObject>){
        name = (dictionary["name"] as? String)!
    }

    public func encode() -> Dictionary<String, AnyObject> {
        var dictionary : Dictionary = Dictionary<String, AnyObject>()
        dictionary["name"] = name as AnyObject?
        return dictionary
    }

}

Usage of the structures and UserDefaults.

let user1 = User(name: "ZeKai").encode()
let user2 = User(name: "Oleg").encode()

let defaults = UserDefaults(suiteName: "User")
defaults?.set(user1, forKey: "User1")
defaults?.set(user2, forKey: "User2")
defaults?.synchronize()

let user1EncodeData = defaults?.dictionary(forKey: "User1")        
let user = User(dictionary: user1EncodeData as! Dictionary<String, AnyObject>)

Upvotes: 1

Related Questions