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];
?
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;
}
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.
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
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];
}
我倾向于认为您应该从负责控制器的-(void)viewDidLoad方法调用此方法
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.