I'm trying to subclass UIView. I already have some designated initializer and I want to have possibility for my custom view to be initialized either from code or from Nib file. So, Apple told us to use designated initializer, but they are not doing it themselves - initWithCoder:
doesn't call initWithFrame:
. What should I do to have my designated initializer be called in both situations? Is there no way to do that?
Asked
Active
Viewed 1.5k times
26

Duncan Babbage
- 19,972
- 4
- 56
- 93

DemoniacDeath
- 1,778
- 3
- 13
- 25
-
Take a look here please and see the code sample http://stackoverflow.com/a/17798646/381807 – nesimtunc Jul 22 '13 at 22:38
2 Answers
42
Pack your special initialization in one method. It can be private (declared in .m). Then override both initializers and call your init-method from within them.
- (void)myInitialization
{
//do your stuff
}
- (id)initWithFrame:(CGRect)aRect
{
self = [super initWithFrame:aRect];
if (self)
{
[self myInitialization];
}
return self;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self myInitialization];
}
return self;
}

Rok Jarc
- 18,765
- 9
- 69
- 124
-
do we not need to include `- (instancetype)init` initializer ..? Just in case. I am new to objective C. – shashwat Jun 13 '14 at 12:00
-
It is not necessary - subclasses of `UIView` are rarely initialized by _simple_ `init`. In same cases it might make sense to include `init` also - ie: if certain type of view would usually be initialized with fixed frame or something like that. – Rok Jarc Jun 13 '14 at 15:49
5
As you said:
initWithFrame: - It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method.
initWithCoder: - Implement this method if you load your view from an Interface Builder nib file and your view requires custom initialization.
What I would do is just a method that both would call, which would have common behavior you want to implement in your UIView
.

Rui Peres
- 25,741
- 9
- 87
- 137