我有一个自定义 View ,我希望能够在 in-code
和 nib
中初始化。
编写 initWithFrame
和 initWithCoder
方法的正确方法是什么?
它们都共享一个用于某些初始化的代码块。
最佳答案
在这种情况下,正确的做法是创建另一个包含 -initWithFrame:
和 -initWithCoder:
通用代码的方法,然后调用该方法来自 -initWithFrame:
和 -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;
}
请注意 Justin 的回答中概述的问题,特别是任何子类不得覆盖 -commonInit
。我在这里使用该名称是为了说明它的值(value),但您可能想要一个与您的类更紧密相关并且不太可能被意外覆盖的名称。如果您正在创建一个不太可能自己被子类化的专用 UIView 子类,那么使用上面的通用初始化方法就完全没问题了。如果您正在编写供其他人使用的框架,或者如果您不了解该问题但想做最安全的事情,请改用静态函数。
关于objective-c - Objective-C - 自定义 View 和实现 init 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226239/