Undefined symbols for architecture armv7 when working with objc_setAssociatedObject

…衆ロ難τιáo~ 提交于 2019-12-25 02:46:16

问题


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,


回答1:


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);



回答2:


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);


来源:https://stackoverflow.com/questions/20740460/undefined-symbols-for-architecture-armv7-when-working-with-objc-setassociatedobj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!