gpt4 book ai didi

objective-c - 在 Objective-C 类中初始化一个静态变量

转载 作者:太空狗 更新时间:2023-10-30 03:27:07 26 4
gpt4 key购买 nike

我试图创建一个静态变量来存储图像字典。不幸的是,我能找到的最好的初始化方法是检查每个使用该变量的函数。因为我是在一个类别中创建这个变量,所以我不能只在初始化程序中初始化它。有没有更简洁的初始化 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

最佳答案

__attribute__((constructor))
static void initialize_navigationBarImages() {
navigationBarImages = [[NSMutableDictionary alloc] init];
}

__attribute__((destructor))
static void destroy_navigationBarImages() {
[navigationBarImages release];
}

这些函数会在程序开始和结束时自动调用。

关于objective-c - 在 Objective-C 类中初始化一个静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2046426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com