![](/img/trans.png)
[英]iOS 9 crash - Unrecognized selector sent to instance; selector is valid property
[英]iOS category property unrecognized selector sent to instance
我有带有属性的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
行。
我究竟做错了什么?
只有一种方法可以将属性添加到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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.