目标C-自定义视图和实现init方法? [英] Objective C - Custom view and implementing init method?
问题描述
我有一个自定义视图,希望能够同时初始化in-code
和nib
.
I have a custom view that I want to be able to initialize both in-code
and in nib
.
同时编写initWithFrame
和initWithCoder
方法的正确方法是什么?
它们都共享一个用于一些初始化的代码块.
What's the correct way to write both initWithFrame
and initWithCoder
methods?
They both share a block of code that is used for some initialization.
推荐答案
在这种情况下,正确的做法是创建另一个包含-initWithFrame:
和-initWithCoder:
通用代码的方法,然后调用该方法来自-initWithFrame:
和-initWithCoder:
:
The right thing to do in that case is to create another method containing the code that's common to both -initWithFrame:
and -initWithCoder:
, and then call that method from both -initWithFrame:
and -initWithCoder:
:
- (void)commonInit
{
// do any initialization that's common to both -initWithFrame:
// and -initWithCoder: in this method
}
- (id)initWithFrame:(CGRect)aRect
{
if ((self = [super initWithFrame:aRect])) {
[self commonInit];
}
return self;
}
- (id)initWithCoder:(NSCoder*)coder
{
if ((self = [super initWithCoder:coder])) {
[self commonInit];
}
return self;
}
请注意贾斯汀的回答中概述的问题,尤其是任何子类都不能覆盖 -commonInit
.我在这里使用该名称是为了说明性的价值,但是您可能想要一个与您的班级联系更紧密并且不太可能被意外覆盖的名称.如果您要创建一个不太可能自己被子类化的专用UIView子类,那么使用上述通用初始化方法就可以了.如果您正在编写供其他人使用的框架,或者如果您不了解问题,但想做最安全的事情,请使用静态函数.
Do heed the concerns outlined in Justin's answer, particularly that any subclasses must not override -commonInit
. I used that name here for its illustrative value, but you'll probably want one that's more closely tied to your class and less likely to be accidentally overridden. If you're creating a purpose-built UIView subclass that's unlikely to be subclassed itself, using a common initialization method as above is perfectly fine. If you're writing a framework for others to use, or if you don't understand the issue but want to do the safest possible thing, use a static function instead.
这篇关于目标C-自定义视图和实现init方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!