Reputation: 45961
I'm developing an iOS app with latest SDK.
I have created a class that inherits from UIView
and I have to do some initialization every time the class is instantiated.
I have to call a method called setUpVars:
but I don't know where to send a message to that method:
- (id)initWithFrame:(CGRect)frame;
- (id)initWithCoder:(NSCoder*)aDecoder;
This class can be used with a custom xib, or added to a Storyboard, so I need to be sure that that method will be called on every case.
- (void)setUpVars
{
_preferenceKey = @"";
_preferenceStatus = NO;
_isDown = NO;
}
Where do I have to add [self setUpVars];
?
Upvotes: 2
Views: 749
Reputation: 42977
If you use Interface Builder to design your interface, initWithFrame
: is not called when your view objects are subsequently loaded from the nib file. Instead initWithCoder
gets called. So you can initialize your variables in both methods if you prefer a generic way. Works in both case
Upvotes: 0
Reputation: 38728
Essentially you will be wanting to cover both cases
- (id)initWithFrame:(CGRect)frame;
{
self = [super initWithFrame:frame];
if (self) {
[self setUpVars];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder;
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setUpVars];
}
return self;
}
Upvotes: 2
Reputation: 20021
Docs Says
awakeFromNib
Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
- (void)awakeFromNib
{
[self setUpVars];
}
Upvotes: 0
Reputation: 1866
I tend to think you should call this method from the -(void)viewDidLoad method of the controller in charge
Upvotes: -1
Reputation: 1433
I think that you need to send this message from each method, also do not forget about awakeFromNib
method.
You can create BOOL
variable, something like isAlreadySetup
and set it to YES
in setUpVars
method.
Upvotes: 0