Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faking instance variables in Objective-C categories with Associative References - Error "Use of undeclared identifier 'OBJC_ASSOCIATION_RETAIN"

I am trying to create "fake" instance variables in categories by using objc_setAssociatedObjectas described in this post.

However, I get the following error using ARC in iOS 6.1: Use of undeclared identifier 'OBJC_ASSOCIATION_RETAIN for the following code snippet:

- (void)setStyleName:(NSString *)styleName
{
   objc_setAssociatedObject(self, kDHStyleKey, styleName,
   OBJC_ASSOCIATION_RETAIN);
}

Has anything changed for iOS 6.1?

What did I miss?

like image 359
AlexR Avatar asked Nov 04 '22 04:11

AlexR


2 Answers

It seems that I did not import: #import <objc/runtime.h>

like image 101
AlexR Avatar answered Nov 13 '22 21:11

AlexR


You must import #import <objc/runtime.h>in order to use associated objects provided by objc-runtime so as to be able to fake instance variables or properties in a category.

Also i would like to point out that using instance varaibles in category gives compile time warning saying that iVars are not allowed in a category but using property in a category doesn't warn you at compile time if you use @dynamic for it. Instead it will lead you to a crash at runtime when you will try to set that property in a class.

like image 26
Deepankar Srivastava Avatar answered Nov 13 '22 21:11

Deepankar Srivastava