在swift中使用关联对象——associated objects

在swift中针对class,还是可以利用oc时代的关联对象在扩展中增加实例字段。不过就像这篇文章的示例 一样,你要定义一个本地变量(private var catKey: UInt8)用来取地址。每次这样定义实在很不方便,于是我就做了个简单处理,针对每一个类创建一个Array来保存关联对象的"key地址",并用字典缓存。

不过这样做以后会存在一个问题:Array必须是固定的,否则动态增加Array时,取"key地址"就会找不到了。默认我设置了最大值是4,也可以通过接口设置实际的值。代码如下:

p.s. 这两天正在学习swift觉得它语法虽然严格但是动态性基本为零。而且没有了KVO,json动态绑定Model和MVVM的绑定机制等就别想实现了。(当然了你也可以选择继续使用NSObject基类)。所以就想利用关联对象为基础写一个简单的KVO,也算是练手了,如果代码风格写的不对还请帮忙指出。

import Foundation

public protocol Initializable {
    init()
}

public protocol AssociatedObjectPropertys {
    var count: Int { get }
}

public enum AssociatedObjectError: Error {
    case KeyIndexOutOfRange
}

// get key pointer
private let lock1 = Mutex()   // 这里直接使用了RAC的PosixThreadMutex实现,就不贴了。如果测试用,把lock的地方注掉就行了
private let lock2 = Mutex()
private var classPropertiesLatestIndexMapper: [String : Int] = [:]
private var classPropertiesIndexesMapper: [String : [String : Int]] = [:]
private var classPropertiesKeysMapper: [String: UnsafeMutableBufferPointer] = [:]

private func getLatestIndex(_ className: String) -> Int {
    if let idx = classPropertiesLatestIndexMapper[className] {
        classPropertiesLatestIndexMapper[className] = idx + 1
    } else {
        classPropertiesLatestIndexMapper[className] = 0
    }
    return classPropertiesLatestIndexMapper[className]!
}

private func getKeyIndex(_ className: String, _ propName: String) -> Int {
    var indexes = classPropertiesIndexesMapper[className]
    guard indexes != nil else {
        lock1.lock()
        defer {
            lock1.unlock()
        }
        let latestIdx = getLatestIndex(className)
        indexes = [propName: latestIdx]
        classPropertiesIndexesMapper[className] = indexes
        return latestIdx
    }

    if let index = indexes![propName] {
        return index
    } else {
        lock1.lock()
        defer {
            lock1.unlock()
        }
        let latestIdx = getLatestIndex(className)
        indexes![propName] = latestIdx
        classPropertiesIndexesMapper[className] = indexes!
        return latestIdx
    }
}

private func getArrayPtr(_ className: String, _ assocObjPropCount: Int) -> UnsafeMutableBufferPointer {
    guard let arrayPtr = classPropertiesKeysMapper[className] else {
        lock2.lock()
        defer {
            lock2.unlock()
        }
        var keys = Array(repeating: 0, count: assocObjPropCount)
        let ptr = UnsafeMutableBufferPointer(start: &keys, count: keys.count)
        classPropertiesKeysMapper[className] = ptr
        return ptr
    }
    return arrayPtr
}

private func getKeyPointer(_ className: String, _ keyIdx: Int, _ assocObjPropCount: Int) throws -> UnsafeMutablePointer {
    guard keyIdx <= assocObjPropCount else {
        throw AssociatedObjectError.KeyIndexOutOfRange
    }

    let arrayPtr = getArrayPtr(className, assocObjPropCount)
    let basePtr = arrayPtr.baseAddress!
    if keyIdx == 0 {
        return basePtr
    } else {
        var nextPtr: UnsafeMutablePointer!
        for _ in 0.. Int {
    guard let instance = object as? AssociatedObjectPropertys else {
        return 4
    }
    return instance.count
}

private func associatedObjectKey(_ object: AnyObject, _ key: String) throws -> UnsafeMutablePointer {
    let className = NSStringFromClass(type(of: object))
    let keyIndex = getKeyIndex(className, key)
    return try getKeyPointer(className, keyIndex, getAssocObjPropsMaxCount(object))
}

// associate object
private func associatedObject(
    _ object: AnyObject,
    _ key: UnsafePointer,
    _ initialiser: @autoclosure () -> ValueType)
    -> ValueType {
        if let associated = objc_getAssociatedObject(object, key)
            as? ValueType {
            return associated
        }

        let associated = initialiser()
        objc_setAssociatedObject(object, key, associated, .OBJC_ASSOCIATION_RETAIN)
        return associated
}

private func associateObject(
    _ object: AnyObject,
    _ key: UnsafePointer,
    _ value: ValueType) {
    objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN)
}

// ----- public methods -----

public func getAssocObj(
    this object: AnyObject,
    prop key: String,
    _ initialiser: @autoclosure () -> ValueType)
    -> ValueType {
        guard let val = try? associatedObject(object, associatedObjectKey(object, key), initialiser) else {
            // todo: add error log
            return initialiser()
        }
        return val
}

public func getAssocObj(
    this object: AnyObject,
    prop key: String)
    -> ValueType {
        guard let val = try? associatedObject(object, associatedObjectKey(object, key), ValueType.init()) else {
            // todo: add error log
            return ValueType.init()
        }
        return val
}

public func setAssocObj(
    this object: AnyObject,
    prop key: String,
    value: ValueType) {
    guard let key = try? associatedObjectKey(object, key) else {
        // todo: add error log
        return
    }
    associateObject(object, key, value)
}

因为get需要默认值,所以利用Initializable协议和泛型推导会让代码更简洁点。测试代码如下:

class Miller {
    init(n catName: String) {
        self.cat.name = catName
    }
}
class Cat: Initializable {
    var name = "Puss"
    
    required init() {}
}

extension Miller: AssociatedObjectPropertys {
    var count: Int {
        get {
            return 16
        }
    }
    var cat: Cat {
        get {
            return getAssocObj(this: self, prop: #function)
        }
        set {
            setAssocObj(this: self, prop: #function, value: newValue)
        }
    }
    
    var age: Int {
        get {
            // 默认值写法与上面不同
            return getAssocObj(this: self, prop: #function, 3)
        }
        set {
            setAssocObj(this: self, prop: #function, value: newValue)
        }
    }
}

let miller = Miller(n: "tom")
print("name: \(miller.cat.name), age: \(miller.age)")
miller.cat.name = "jerry"
miller.age = 18
print("name: \(miller.cat.name), age: \(miller.age)")

你可能感兴趣的:(在swift中使用关联对象——associated objects)