Majky
Majky

Reputation: 2013

iOS category property unrecognized selector sent to instance

I've Objective-C category for iOS 7.1 with property...here's header code

#import <UIKit/UIKit.h>

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

then I've .m file with code

#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.

What am I doing wrong?

Upvotes: 2

Views: 2905

Answers (1)

Thomas Keuleers
Thomas Keuleers

Reputation: 6115

There's only 1 way to add properties to an objective-c category: that is by using associated objects.

Please use this guide to fix your code:

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:

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

Upvotes: 9

Related Questions