简体   繁体   中英

Undefined symbols for architecture armv7 when working with objc_setAssociatedObject

This is the run time error log I am getting:

Undefined symbols for architecture armv7:
  "_MyConstantKey", referenced from:
      -[LayoutViewController addLabelsAndButtonInBaseView:withLayoutObject:] in LayoutViewController.o
ld: symbol(s) not found for architecture armv7

I am trying to pass an object along with UIButton selector.

this is my code:

this is how I am declaring a var:

extern const char MyConstantKey;
@interface LayoutViewController : UIViewController

my implementation file :

#import <objc/runtime.h>

and relevant code for setting associated object:

UIButton *componentButton = [[UIButton alloc] initWithFrame:baseView.bounds];
objc_setAssociatedObject(componentButton,
                         MyConstantKey,
                         layout,
                         OBJC_ASSOCIATION_RETAIN);
[componentButton addTarget:self
                action:@selector(componentButtonPressed:)
      forControlEvents:UIControlEventTouchUpInside];
[componentButton setTitle:@"" forState:UIControlStateNormal];

any suggestion? Is there any framework which I am missing,

Declaring variable as extern only prompts to compiler that variable will be created somewhere possibly outside of current compilation unit. So you need to actually create it in your implementation file. Also I think using char* instead of char here will be more appropriate:

// .h
extern const char* MyConstantKey;

// .m 
const char* MyConstantKey = "MyConstantKey"; 

…
objc_setAssociatedObject(componentButton,
                         (void*)MyConstantKey,
                         layout,
                         OBJC_ASSOCIATION_RETAIN);

Define your custom property like this way

#define kCustomProperty @"CustomProperty" 

Associate your object with that custom property like below

objc_setAssociatedObject(myObj,kCustomProperty , myData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

Get your data using the same property and object like below

NSObject *aObj = objc_getAssociatedObject(myObj, kCustomProperty);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM