简体   繁体   中英

UIView subclass throwing “Selector not found” when calling UIView+Category method

I have subclass of UIView, MyView. I also have a category on UIView called UIView+simpleCategory.

This category declares a method doSomething

@interface UIView (simpleCategory)

- (void) doSomething;

@end

I'm having problems calling the doSomething method from the UIView subclass MyView. I get a "selector not recognized" error. I was wondering what I would need to do to have the subclass recognize its super class's category methods.

The problem arises when calling the UIView category method on an instance of my UIView subclass :

MyView *view = [[MyView alloc] init];
[view doSomething];        // throws selector not found error here

I'm wondering if I'm missing a #import somewhere but I would like to understand the relationship between Category and Subclasses.

THE SOLUTION ::

Apparently my implementation was fine. I just needed to add the category to the app target. I did this by clicking the category in the Project Navigator. Then I clicked the Utilities View (the view that slides out from the right side of the window) and checked the "Target Membership" checkbox in the File Inspector menu. This was all that needed to be done. Thanks everyone for the responses.

Your project is finding the header file declaring the UIView category — otherwise you'd get a compile-time warning.

But at run-time, it's not finding the category method. Check your UIView category implementation file to see which targets it goes into. I'm betting it's not included in your main target.

Well, here's what I did to test this, and it worked.

The category:

@interface UIView (simpleCategory)

-(void)doSomething;

@end

@implementation UIView (simpleCategory)

-(void)doSomething {
    NSLog(@"Doing something");
}

I created a UIView subclass, MyView, to which I added no code except to import the category:

#import <UIKit/UIKit.h>
#import "UIView+simpleCategory.h"

@interface MyView : UIView

@end

Then in my view controller viewDidLoad method:

MyView *view = [[MyView alloc] init];
[view doSomething];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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