简体   繁体   English

子类中的alloc和init

[英]alloc and init in a subclass

I have subclassed UIView and provided my own drawRect, which works fine. 我已经继承了UIView并提供了自己的drawRect,效果很好。 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. 我认为无论何时创建子类的对象(通过Interface Builder发生),都会调用alloc和init方法。 However the object IS created, but my init and alloc don't get called. 但是对象是创建的,但是我的init和alloc没有被调用。 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? 另外,构建会产生警告,提示UIView可能不会响应“ alloc”-它不是必须从NSObject继承它吗?或者如何正确创建UIView?

My objective in the above was that my subclassed view would be able to do custom initialization after IB got it created. 我在上面的目标是我的子视图将能够在IB创建它之后进行自定义初始化。

init is not the designated initializer for UIView ; init不是UIView的指定初始值设定项; initWithFrame: is. initWithFrame:是。 If you override initWithFrame: , it should get called, but init never gets called by UIView . 如果重写initWithFrame:则应调用它,但UIView永远不会调用init

You're right about alloc , it's a class method. 你说得对, alloc ,这是一个类的方法。 UIViews use initWithFrame: for initialisation, so look into overriding that. UIViews使用initWithFrame:进行初始化,因此请研究覆盖它。

Apple generally builds their init overrides like this: Apple通常构建他们的init覆盖,如下所示:

-(id)init{
   self = [super init];
    if (self) {
          //Custom Initialization goes here
     }
}

Though the above commenters are correct. 虽然以上评论者都是正确的。 initwithFrame: is the designated initializer However, the override as you formatted your question will get you a compiler warning for your trouble. initwithFrame:是指定的初始值设定项。但是,格式化问题时的覆盖将使您收到编译器警告您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM