Created
January 21, 2017 20:50
-
-
Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.
Example to instantiate models only once and update them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Weak<T: AnyObject> { | |
weak var value : T? | |
init (value: T) { | |
self.value = value | |
} | |
} | |
public class Model { | |
let id: String | |
private init(from payload: JSON) { | |
... | |
} | |
private static var instanciated = [String: Weak<Model>]() | |
deinit { | |
if Model.instanciated[id]?.value === self { | |
Model.instanciated.removeValue(forKey: id) | |
} | |
} | |
private static func getCacheOrCache(model: Model) -> Model { | |
if let existingInstance = instanciated[model.id]?.value { | |
update(cached: existingInstance, with: model) | |
return existingInstance | |
} | |
instanciated[model.id] = Weak<Model>(value: model) | |
return model | |
} | |
private static func update(cached instance: Model, with update: Model) { | |
instance.someField = update.someField | |
} | |
static func create(from payload: JSON) Model { | |
let model = Model(from: payload) | |
return getCacheOrCache(model: model) | |
} | |
} | |
// then instead of doing `let m = Model(…)`, you do `let m = Model.create(…)` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment