Skip to content

Instantly share code, notes, and snippets.

@gsabran
Created January 21, 2017 20:50
Show Gist options
  • Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.
Save gsabran/713a770a224f21638c12b25fd668c1b6 to your computer and use it in GitHub Desktop.

Revisions

  1. gsabran created this gist Jan 21, 2017.
    39 changes: 39 additions & 0 deletions UniquelyInstanciatedModels.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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(…)`