iOS类别属性无法识别的选择器发送到实例

时间:2014-03-25 14:42:41

标签: ios objective-c

我有iOS 7.1的Objective-C类别,带有属性......这里是标题代码

#import <UIKit/UIKit.h>

@interface UIViewController (CategoryName)
@property(nonatomic, copy) UITapGestureRecognizer *recognizer;

然后我的.m文件包含代码

#import "UIViewController+CategoryName.h"

@implementation UIViewController (CategoryName)
@dynamic recognizer;

...

- (void)myMethod {
    // here it crashes!!!
    self.recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(anothermethod)];
    ...
}


...

@end

将类别导入到viewcontroller中,然后调用[self myMethod]始终崩溃并显示消息 - unrecognized selector sent to instance指向myMethod中初始化self.recognizer的行。

我做错了什么?

1 个答案:

答案 0 :(得分:9)

只有一种方法可以将属性添加到 objective-c类别:即使用关联对象

请使用本指南修复您的代码:

http://www.davidhamrick.com/2012/02/12/Adding-Properties-to-an-Objective-C-Category.html

另外,NSHipster在这个主题上写了一篇博文,并且很好地解释了这个问题:

http://nshipster.com/associated-objects/

要完全帮助您摆脱困境,请参阅以下代码来解决问题:

#import <objc/runtime.h>

NSString * const recognizerPropertyKey = @"recognizerPropertyKey";

@implementation UIViewController (CategoryName)
@dynamic recognizer;

- (void)setRecognizer:(UITapGestureRecognizer *)recognizer {
    objc_setAssociatedObject(self, (__bridge const void *)(recognizerPropertyKey), recognizer, OBJC_ASSOCIATION_COPY);
}

- (UITapGestureRecognizer *)recognizer {
        return objc_getAssociatedObject(self, (__bridge const void *)(recognizerPropertyKey));
}

@end