2011-09-30 55 views
14

我创建了一个类别UINavigationBar的用下面的代码:的ObjectiveC类别不进口,但仍运行代码

// 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 

我没有任何地方不过#进口,在任何代码在我的整个项目,此类别仍在运行并插入标题图形。这怎么可能?

回答

24

因为编译代码时会在代码中包含代码。 #import只是使当前上下文(.h.m)知道该类别中的方法。

编译到您的应用中的任何类别都会在您的应用运行时随时加载。

要删除添加到目标的类别,请从应用的Target->Build Phase->Compile Sources中删除类别.m文件。

假设您需要一些导航栏来使用此代码,但不是所有这些代码,最好的方法是使用UINavigationBar。 (你要打电话[super drawRect:rect]在你的子类,顺便说一句)

编辑:增加UINavigationBar的图像的另一种方法,

在你想要的形象出现在任何视图控制器,只需添加self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header.png"]] autorelease];viewWillAppear:

+1

'编译到您的应用中的任何类别都会在您的应用运行时随时加载。'很高兴知道,thx! – Philip007