关联对象API使用起来有点麻烦。您可以使用帮助程序类删除大部分样板。
public final class ObjectAssociation<T: AnyObject> { private let policy: objc_AssociationPolicy /// - Parameter policy: An association policy that will be used when linking objects. public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) { self.policy = policy } /// Accesses associated object. /// - Parameter index: An object whose associated object is to be accessed. public subscript(index: AnyObject) -> T? { get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? } set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) } }}
前提是您可以以更易读的方式将属性“添加”到objective-c类:
extension SomeType { private static let association = ObjectAssociation<NSObject>() var simulatedProperty: NSObject? { get { return SomeType.association[self] } set { SomeType.association[self] = newValue } }}
至于解决方案:
extension CALayer { private static let initialPathAssociation = ObjectAssociation<CGPath>() private static let shapeLayerAssociation = ObjectAssociation<CAShapeLayer>() var initialPath: CGPath! { get { return CALayer.initialPathAssociation[self] } set { CALayer.initialPathAssociation[self] = newValue } } var shapeLayer: CAShapeLayer? { get { return CALayer.shapeLayerAssociation[self] } set { CALayer.shapeLayerAssociation[self] = newValue } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)