Mikuro
Crotchety UI Nitpicker
What's the proper way to create initialization code in a class that is always (and only) run once?
I'm creating a custom view class, and the relationship between awakeFromNib and initWithFrame: has me a little confused. There are three ways to create an instance, and each has different behavior.
1. If I create an NSScrollView in Interface Builder by selecting some controls in a window, choosing "Make subviews of > Scroll view", and then change its custom class to my subclass, then only awakeFromNib is called.
2. If I create a Custom View in Interface Builder and assign it any custom class, then initWithFrame fires, and then awakeFromNib ALSO fires.
3. Naturally, when I create an instance through code, only initWithFrame fires.
So how should I manage my initialization code in such a way that it'll work properly all three ways I mentioned above? Clearly I need to call my initialization code in both initWithFrame and awakeFromNib, but I don't want it to fire TWICE, as would happen in case #2.
The first thought I had was to simply create an instance variable, "BOOL didAlreadyInitialize", set it whenever I called my initialization code, and check that it was not set before calling my code again. But.....then there's the problem of how I initialize that instance variable. I can't count on it being false when the object is created, can I?
It seems like such a simple problem, but I'm having a little trouble coming up with a simple solution. What am I missing?
I'm creating a custom view class, and the relationship between awakeFromNib and initWithFrame: has me a little confused. There are three ways to create an instance, and each has different behavior.
1. If I create an NSScrollView in Interface Builder by selecting some controls in a window, choosing "Make subviews of > Scroll view", and then change its custom class to my subclass, then only awakeFromNib is called.
2. If I create a Custom View in Interface Builder and assign it any custom class, then initWithFrame fires, and then awakeFromNib ALSO fires.
3. Naturally, when I create an instance through code, only initWithFrame fires.
So how should I manage my initialization code in such a way that it'll work properly all three ways I mentioned above? Clearly I need to call my initialization code in both initWithFrame and awakeFromNib, but I don't want it to fire TWICE, as would happen in case #2.
The first thought I had was to simply create an instance variable, "BOOL didAlreadyInitialize", set it whenever I called my initialization code, and check that it was not set before calling my code again. But.....then there's the problem of how I initialize that instance variable. I can't count on it being false when the object is created, can I?
It seems like such a simple problem, but I'm having a little trouble coming up with a simple solution. What am I missing?