Swift 2.0 replicate OBJC_ASSOCIATION_RETAIN

徘徊边缘 提交于 2019-12-23 11:47:01

问题


I'm extending some classes in Swift 2.0 to work with ReactiveCocoa 3.0 (swift-2.0 branch), but have run into some trouble.

I've followed Colin Eberhardt's tutorial, and have copy pasted some of his UIKit extension logic over to my OS X app. It all compiles fine, apart from this property: UInt(OBJC_ASSOCIATION_RETAIN), which gives me the following compiler error.

use of unresolved identifier

How can I access this property? I've tried to import ObjectiveC and #import <objc/runtime.h> in the header file, but nothing seems to work.

func lazyAssociatedProperty<T: AnyObject>(host: AnyObject, key: UnsafePointer<Void>, factory: ()->T) -> T {
    return objc_getAssociatedObject(host, key) as? T ?? {
        let associatedProperty = factory()

        objc_setAssociatedObject(host, key, associatedProperty, UInt(OBJC_ASSOCIATION_RETAIN)) // <-- Use of unresolved identifier
        return associatedProperty
    }()
}

回答1:


This is actually now imported into Swift as an enum named objc_AssociationPolicy. Definition:

enum objc_AssociationPolicy : UInt {
    case OBJC_ASSOCIATION_ASSIGN
    case OBJC_ASSOCIATION_RETAIN_NONATOMIC
    case OBJC_ASSOCIATION_COPY_NONATOMIC
    case OBJC_ASSOCIATION_RETAIN        
    case OBJC_ASSOCIATION_COPY
}

Meaning that it can be used as follows.

objc_setAssociatedObject(host, key, associatedProperty, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)

Or with enum shorthand syntax.

objc_setAssociatedObject(host, key, associatedProperty, .OBJC_ASSOCIATION_RETAIN)

Note that objc_setAssociatedObject has also been updated to take a objc_AssociationPolicy argument instead of UInt making it unnecessary to access the enum's rawValue here.



来源:https://stackoverflow.com/questions/30872626/swift-2-0-replicate-objc-association-retain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!