23

I just updated my project to Swift 2.

I one of my swift class I use ObjC association.

I have the following :

objc_AssociationPolicy( OBJC_ASSOCIATION_RETAIN_NONATOMIC)

Since the update, the compiler returns Use of unresolved identifier 'OBJC_ASSOCIATION_RETAIN_NONATOMIC'.

Any idea why ?


Edit: For those who have the same problem, a temporary fix would be to replace the constant with its value ie. 1 : objc_AssociationPolicy( rawValue: 1 )

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • Possible duplicate of [Swift 2.0 replicate OBJC\_ASSOCIATION\_RETAIN](http://stackoverflow.com/questions/30872626/swift-2-0-replicate-objc-association-retain) – Mick MacCallum Apr 02 '16 at 18:12

2 Answers2

44

If you look at the obj c runtime swift header, it appears this construct has become an enum:

/**
 * Policies related to associative references.
 * These are options to objc_setAssociatedObject()
 */
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
}

So you can replace with: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC.

If you need the token as a UInt, you can always use .rawValue.

(In the previous version objc_AssociationPolicy was just a typealias for UInt - with the effect of casting 'OBJC_ASSOCIATION_RETAIN_NONATOMIC', an Int)

James Alvarez
  • 7,159
  • 6
  • 31
  • 46
0

Try this:

import ObjectiveC.runtime

func setOverlay(view: UIView)
{
    objc_setAssociatedObject(self, &AssociatedKeys.overlayKey, view, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
Tom Sabel
  • 3,935
  • 33
  • 45