简体   繁体   English

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

[英]iOS category property unrecognized selector sent to instance

I've Objective-C category for iOS 7.1 with property...here's header code 我有带有属性的iOS 7.1 Objective-C类别...这里的标头代码

#import <UIKit/UIKit.h>

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

then I've .m file with code 然后我有带代码的.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

Importing category into viewcontroller and then calling [self myMethod] always crashes with message - unrecognized selector sent to instance pointing to line in myMethod where self.recognizer is initialized. 将类别导入到viewcontroller中,然后调用[self myMethod]总是会因消息而崩溃- unrecognized selector sent to instance指向myMethod中初始化self.recognizer行。

What am I doing wrong? 我究竟做错了什么?

There's only 1 way to add properties to an objective-c category : that is by using associated objects . 只有一种方法可以将属性添加到Objective-C类别中 :即使用关联的对象

Please use this guide to fix your code: 请使用此指南来修复您的代码:

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

Also, NSHipster did a blogpost on this subject and explains this matter really well: 另外,NSHipster在此主题上做了一个博客文章,并很好地解释了这一问题:

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

To completely help you out of trouble, here's the code you should write to fix your problem: 为了完全帮助您摆脱困境,以下是您应编写的用于解决问题的代码:

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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