问题
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