它是正确/ ellegant使用只有alloc没有init? [英] Would it be correct/ellegant use only alloc without init?

查看:120
本文介绍了它是正确/ ellegant使用只有alloc没有init?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们不想在我们的类中实现init方法,并且记住NSObject中的init只返回没有初始化的对象的实例,如果我们已经得到了实例与alloc。我已经尝试,它的工作,但我不知道这不会导致未来的问题。

If we don't want to implement init method in our class, and bearing in mind that init in NSObject only returns an instance of the object without initialization, I don't see the point of calling init if we already get the instance with alloc. I have tried and it works, but I am not sure it won't cause future problems.

myClass *newObject = [myClass alloc];

而不是:

myClass *newObject = [[myClass alloc] init];

非常感谢。

推荐答案

不,只是调用 alloc 将不正确。 alloc 将对象的所有实例变量清零, init 然后有机会将所有或一些实例变量设置为默认值。一些类甚至使用他们的 init 方法来创建另一个实例,并返回一个而不是你分配的实例。

No, just calling alloc would not be correct. alloc zeroes out all instance variables of the object, init then has the chance to set all or some instance variables to their default values. Some classes even use their init methods to create another instance and return that one instead of the one you allocated.

许多类期望他们的 init 方法被调用,如果你不调用 init ,可能会导致崩溃。如果你正在谈论一个直接从 NSObject 继承并且不需要初始化实例变量的自定义类,那么你可能会失去 [myClass alloc] 但它绝对不是好的编程风格。

Many classes expect that their init methods get called and would possibly cause crashes if you don't call init. If you are talking about a custom class that inherits directly from NSObject and needs no initialization of instance variables, you might get away with [myClass alloc] but it is definitely not good programming style.

这篇关于它是正确/ ellegant使用只有alloc没有init?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆