子类中的 alloc 和 init
我已经对 UIView 进行了子类化并提供了我自己的drawRect,它工作得很好。不过,我将这些方法添加到了我的子类中:
- (id) alloc
{
NSLog(@"Alloc");
return [super alloc];
}
- (id) init
{
NSLog(@"Init");
if (self = [super init])
flashWhite = true;
return self;
}
我认为每当创建子类的对象(通过 Interface Builder 发生)时,都会调用 alloc 和 init 方法。然而,对象已创建,但我的 init 和 alloc 没有被调用。难道不应该发生这种情况以确保正确的初始化吗?
另外,构建会产生一个警告,指出 UIView 可能不会响应“alloc”——它是否必须从 NSObject 继承它,或者如何正确创建 UIView?
上面我的目标是我的子类视图能够在 IB 创建后进行自定义初始化。
I have subclassed UIView and provided my own drawRect, which works fine. However I added these methods to my subclass:
- (id) alloc
{
NSLog(@"Alloc");
return [super alloc];
}
- (id) init
{
NSLog(@"Init");
if (self = [super init])
flashWhite = true;
return self;
}
I thought that whenever an object of the subclass is created (which happens through Interface Builder), the alloc and init methods would get called. However the object IS created, but my init and alloc don't get called. Shouldn't this happen to ensure proper initialization?
Also, building produces a warning that UIView may not respond to 'alloc' - doesn't it have to inherit this from NSObject, or how could a UIView be properly created?
My objective in the above was that my subclassed view would be able to do custom initialization after IB got it created.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
init
不是UIView
的指定初始化器;initWithFrame:
是。如果您重写initWithFrame:
,它应该被调用,但init
永远不会被UIView
调用。init
is not the designated initializer forUIView
;initWithFrame:
is. If you overrideinitWithFrame:
, it should get called, butinit
never gets called byUIView
.alloc
你是对的,它是一个类方法。 UIViews 使用initWithFrame:
进行初始化,因此请考虑覆盖它。You're right about
alloc
, it's a class method. UIViews useinitWithFrame:
for initialisation, so look into overriding that.苹果通常这样构建他们的 init 覆盖:
尽管上述评论者是正确的。
initwithFrame:
是指定的初始化器然而,当你格式化你的问题时,覆盖将会给你一个编译器警告。
Apple generally builds their init overrides like this:
Though the above commenters are correct.
initwithFrame:
is the designated initializerHowever, the override as you formatted your question will get you a compiler warning for your trouble.