ObjectiveC类别未导入但仍在运行代码 [英] ObjectiveC Category is not imported but still running code

查看:97
本文介绍了ObjectiveC类别未导入但仍在运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码为UINavigationBar创建了一个类别:

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

我没有#import随时随地但是,在我整个项目的任何代码中,此类别仍在运行并插入标题图形。这怎么可能?

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?

推荐答案

因为您在编译时将代码包含在应用程序中。 #import 只生成当前上下文( .h .m )了解该类别中的方法。

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.

假设您希望某些导航栏使用此代码,但不是所有导航栏,最好的方法是将UINavigationBar子类化。 (顺便说一下,你要在你的子类中调用 [super drawRect:rect]

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)

编辑:将图像添加到UINavigationBar的替代方法,

alternate method of adding an image to UINavigationBar,

在任何希望图像显示的视图控制器中,只需添加 self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@header.png]] autorelease]; viewWillAppear:

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:

这篇关于ObjectiveC类别未导入但仍在运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆