子类中的 alloc 和 init

发布于 2024-10-01 05:27:08 字数 521 浏览 2 评论 0原文

我已经对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

Oo萌小芽oO 2024-10-08 05:27:08

init 不是 UIView 的指定初始化器; initWithFrame:是。如果您重写 initWithFrame:,它应该被调用,但 init 永远不会被 UIView 调用。

init is not the designated initializer for UIView; initWithFrame: is. If you override initWithFrame:, it should get called, but init never gets called by UIView.

我最亲爱的 2024-10-08 05:27:08

alloc 你是对的,它是一个类方法。 UIViews 使用 initWithFrame: 进行初始化,因此请考虑覆盖它。

You're right about alloc, it's a class method. UIViews use initWithFrame: for initialisation, so look into overriding that.

唔猫 2024-10-08 05:27:08

苹果通常这样构建他们的 init 覆盖:

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

尽管上述评论者是正确的。 initwithFrame:是指定的初始化器
然而,当你格式化你的问题时,覆盖将会给你一个编译器警告。

Apple generally builds their init overrides like this:

-(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文