开发者

Adding a category to UIImage in iPhone

I want to add a category to UIImage and link it to my iPhone app, but I got this error:

开发者_Python百科

(unrecognized selector)

My code: DoingStuff.h

#import <UIKit/UIKit.h>

@interface UIImage (DoingStuff)

- (UIImage *)performStuff;

@end

DoingStuff.m

#import "DoingStuff.h"

@implementation UIImage (DoingStuff)

- (UIImage *)performStuff 
{
    // My code here
}

@end

But when I run my program I get this :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView performStuff:]: unrecognized selector sent to instance 0x4b415d0'


[UIImage performStuff]; // Correct call

not

[UIImageView performStuff]; // It is a UIImage category not UIImageView

for starters.

So you would do something like this...

UIImage* image = [UIImage imageNamed:@"test"];
[image performStuff];


If the category is in the target project just include the DoingStuff.h. If inside a static library the linker will not link it in, because it doesn't know it should link objective c objects it doesn't know will be used.

You need to put one of -all_load, -force_load or -ObjC in other linker options in you target project. Different people report some or all of them make linker work. Starting with XCode 4 -ObjC should be enough.

That said I didn't have success with any of them and ended in adding the categories from the library to the target project as references.

EDIT

Just saw my mistake, probably it gets linked but is a instance method and you are calling it as a class method:

not

[UIImage performStuff];

but

UIImage *image = <your image>;
[image performStuff];


According to how you have your category set up, you would then need to call it like this:

UIImage* myImage = [UIImage imageNamed:@"testImage"];
[myImage performStuff];

Additionally, you aren't following the naming conventions for categories. Your class name should be something more like "`UIImage+DoingStuff.h". I would suggest refactoring it so that it's more clear to others that it's a category.

And of course, you need to import the header file into the class you want to use it in:

#import "DoingStuff.h"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜