Skip to content

Instantly share code, notes, and snippets.

@gsabran
Created January 21, 2017 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.
Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.
Example to instantiate models only once and update them
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