VansFannel
VansFannel

Reputation: 45961

Custom UIView with custom initialization doesn't work

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

Answers (5)

Anil Varghese
Anil Varghese

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

Paul.s
Paul.s

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

Lithu T.V
Lithu T.V

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

Jerome Diaz
Jerome Diaz

Reputation: 1866

I tend to think you should call this method from the -(void)viewDidLoad method of the controller in charge

Upvotes: -1

Artem Shmatkov
Artem Shmatkov

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

Related Questions