【发布时间】:2011-01-04 00:33:00
【问题描述】:
我试图创建一个静态变量来存储图像字典。不幸的是,我能找到的最好的初始化方法是检查每个使用该变量的函数。由于我在一个类别中创建这个变量,我不能只在初始化程序中初始化它。有没有更简洁的方法来初始化 navigationBarImages?
static NSMutableDictionary *navigationBarImages = NULL;
@implementation UINavigationBar(CustomImage)
//Overrider to draw a custom image
- (void)drawRect:(CGRect)rect
{
if(navigationBarImages==NULL){
navigationBarImages=[[NSMutableDictionary alloc] init];
}
NSString *imageName=[navigationBarImages objectForKey:self];
if (imageName==nil) {
imageName=@"header_bg.png";
}
UIImage *image = [UIImage imageNamed: imageName];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
//Allow the setting of an image for the navigation bar
- (void)setImage:(UIImage*)image
{
if(navigationBarImages==NULL){
navigationBarImages=[[NSMutableDictionary alloc] init];
}
[navigationBarImages setObject:image forKey:self];
}
@end
【问题讨论】:
-
我不鼓励用 NULL 初始化 Obj-c 对象,你应该用 nil 初始化它!
-
@DanielSanchez,虽然我同意,但实际上,nil 只是将 NULL 转换为对象。
-
@FireLizzard nil 相当于指向对象的指针的 NULL。 nil 和 NULL 不能互换。 NULL 的定义与 nil 不同。 nil 定义为 (id)0。 NULL 不是。
标签: objective-c initialization categories static-variables