Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectiveC Category is not imported but still running code

I have created a category for UINavigationBar with the following code:

// UINavigationBar+MyNavigationBar.m
@interface UINavigationBar (MyNavigationBar)

@end

@implementation UINavigationBar (MyNavigationBar)

- (void)drawRect:(CGRect)rect
{
    UIImage *img = [UIImage imageNamed: @"header.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

I have not #import anywhere, in any of the code in my entire project, however, this category is still running and inserting the header graphic. How is this possible?

like image 935
nullfox Avatar asked Sep 30 '11 00:09

nullfox


1 Answers

Because you're including the code in your app when you compile it. #import just makes the current context (.h or .m) aware of the methods in that category.

Any category that is compiled into your app will be loaded at all times while your app is running.

To remove the category from being added to your target remove the category .m file from your app's Target->Build Phase->Compile Sources.

Assuming you want SOME of your navigation bars to use this code, but not ALL of them, the best way to do that is probably to subclass UINavigationBar. (You'll want to call [super drawRect:rect] in your subclass, by the way)

Edit: alternate method of adding an image to UINavigationBar,

In any view controller you want the image to appear, just add self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header.png"]] autorelease]; to viewWillAppear:

like image 178
Kenny Winker Avatar answered Sep 24 '22 14:09

Kenny Winker