9

I was trying to create a static variable to store a dictionary of images. Unfortunately, the best way I could find to initialise it was to check in each function that used the variable. Since I am creating this variable inside a category, I can't just initialise it inside the initialiser. Is there a neater way of initialising 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
4
  • I discourage to initialise an Obj-c object with NULL, you should initialise it with nil! Apr 11, 2012 at 9:42
  • @DanielSanchez, while I would agree, in reality, nil is just NULL cast as an object. May 8, 2014 at 4:17
  • @FireLizzard nil is the equivalent of NULL for a pointer to an object. nil and NULL should not be interchangeable. NULL is differently defined than nil. nil is defined as (id)0. NULL isn't. May 8, 2014 at 9:10
  • nshipster.com/nil May 8, 2014 at 10:48

5 Answers 5

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

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

These function will be called automatically when the program starts and ends.

2
  • 2
    I like this better than +initializer.
    – neevek
    Jul 14, 2012 at 4:03
  • 4
    I don't get it.. Where does this go? Written just like that? And what is supposed to happen?
    – Alex Gray
    Apr 3, 2013 at 13:56
10

Consider this approach,

static NSMutableDictionary *navigationBarImages()
{
    static NSMutableDictionary *dict = NULL;
    if(dict == NULL)
    {
        dict = [[NSMutableDictionary alloc] init];
    }
    return [[dict retain] autorelease];
}

then whenever you woulde use navigationBarImages, replace it with navigationBarImages(), like this:

change

NSString *imageName=[navigationBarImages objectForKey:self];

to

NSString *imageName=[navigationBarImages() objectForKey:self];

If the function call overhead bothers you, maybe use a temporary variable to catch the return of navigationBarImages(),

NSMutableDictionary *dict = navigationBarImages();
[dict doSomething];
[dict doSomething];

The drawback is once you called navigationBarImages(), the instance of NSMutableDictionary got created, then it'll never get chance to dealloc until the end of the program.

2
  • 2
    This lifetime is typical for static variables though, so I wouldn't really consider it a drawback per se. Jan 12, 2010 at 3:30
  • 1
    This isn't going to be quite as threadsafe as using dispatch_once to initialize the dictionary. The code would be better to use: static dispatch_once_t once; static NSMutableDictionary *dict = nil; dispatch_once(&once, ^{ dict = [[NSMutableDictionary alloc] init]; }); return dict;
    – Streeter
    Mar 31, 2014 at 16:06
2

All you need is to set your static once at a known point before it is used. For example, you can set an NSApplication delegate and have it do the work in -applicationDidFinishLaunching:

5
  • I can't access it in another file - static variables are only declared within the scope of a class
    – Casebash
    Jan 12, 2010 at 3:11
  • 2
    Just define a standalone setup function.
    – Jon Reid
    Jan 12, 2010 at 3:18
  • 1
    Nope. That won't work. Something has to call the setup function.
    – bbum
    Jan 12, 2010 at 6:03
  • 1
    But that's what I meant, Bill. Provide a setup function, advertise it in a header file, and call it from -applicationDidFinishLaunching:
    – Jon Reid
    Jan 12, 2010 at 6:08
  • 1
    (By "standalone," I meant "plain ol' C function.")
    – Jon Reid
    Jan 12, 2010 at 7:11
1

One option is to use C++. Change the file's extension to .mm and replace = NULL with [[NSMutableDictionary alloc] init].

0
0

You could add +initialize in the .m file of your category — you'll just need to make sure you're not smashing an existing implementation or you'll get general wonkiness. (Obviously, you can be sure of this if you wrote the code, but with third-party code, this is probably not the best approach.)

4
  • 1
    ...and how are you going to be sure? Bad idea.
    – benzado
    Jan 12, 2010 at 3:42
  • You could certainly be sure if you wrote the class, or you can use runtime introspection methods or similar approaches. I generally only use +initialize in my own source, I was just putting it out there as an option. Frequently, it is the best option, just not with categories. Jan 12, 2010 at 4:30
  • If you wrote the class, you don't need to put +initialize in a category. If you didn't write it, you can't trust that you won't be stomping on it in a future version of the library. Putting +initialize in a category is more risk than it's worth.
    – benzado
    Jan 13, 2010 at 9:41
  • It probably is riskier and more trouble than it's worth in most cases, but I disagree that you'd never need/want to put +initialize in a category. For example, I may have written library/framework code, but only want the static variable and initialization in one client project. I was just trying to provide an alternative that is appropriate in some cases — let's not get militant about it... :-) Jan 13, 2010 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.