Skip to content

Instantly share code, notes, and snippets.

@dotNetTree
Last active May 1, 2018 01:12
Show Gist options
  • Save dotNetTree/f8b37d8f2d3eab56239bd1a72025af4d to your computer and use it in GitHub Desktop.
Save dotNetTree/f8b37d8f2d3eab56239bd1a72025af4d to your computer and use it in GitHub Desktop.
WeakMap
//
// WeakMap.swift
// dotNetTree
//
// Created by SeungChul Kang on 2018. 5. 1..
// Copyright © 2018년 motel. All rights reserved.
//
import Foundation
class WeakMap<K: AnyObject, V: AnyObject> {
private var mapTable: NSMapTable<K, V>
init(keyOptions: NSPointerFunctions.Options, valueOptions: NSPointerFunctions.Options) {
mapTable = NSMapTable.init(keyOptions: keyOptions, valueOptions: valueOptions)
}
static func instance() -> WeakMap2<K, V> {
return WeakMap2.init(keyOptions: .weakMemory, valueOptions: .strongMemory)
}
var description: String {
return mapTable.description
}
subscript(key: K) -> V? {
set { mapTable.setObject(newValue, forKey: key) }
get { return mapTable.object(forKey: key) }
}
}
/* 사용예제
extension UIViewController {
static var store = WeakMap<UIViewController, NSMutableDictionary> = WeakMap.instance()
}
class TestVC: UIViewController {
// 각종 코드
}
extension TestVC {
func test() {
let store = TestVC.store[self] ?? NSMutableDictionary.init()
// 여기서부터 자유롭게 store 데이터를 넣고 빼고 하면 됨.
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment