Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 replicate OBJC_ASSOCIATION_RETAIN

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
    }()
}
like image 602
Chris Avatar asked Jun 16 '15 15:06

Chris


1 Answers

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.

like image 109
Mick MacCallum Avatar answered Nov 16 '22 00:11

Mick MacCallum