Object-c基础编程学习笔记-对象初始化

来源:互联网 发布:石家庄网络兼职 编辑:程序博客网 时间:2024/06/06 03:19

1、对象分配

alloc方法,做了两件事:一件是为类分配一块足够大内存,以存放该类的全部实例变量;另一件事就是,将这块区域中的所有实例变量初始化为0(BOOL初始化为NO,对象初始化为nil)

init方法,从OS中取得一块内存,准备用于存储对象。init几乎总是返回他们正在初始化的对象。

Car *car = [[Car alloc]init];

Car *car = [Car alloc];[car init];
这里一定要使用嵌套,因为初始化的对象,与分配的对象,可能不同

在这里,笔者有一个疑问,既然alloc方法已经为对象分配空间并初始化为0了,那为什么仍然要调用init。看了一些论坛,他们说init负责将对象初始化为0,难道我的书是盗版的?于是我写了一个程序,对于对象,只alloc,而不进行init,然后打印一个int的成员变量,结果是0,很显然,alloc已经初始化了。于是我找到了apple的官网,看到了如下的描述:

Discussion

The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to0.

You must use an init... method to complete the initialization process. For example:

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

Do not override alloc to include initialization code. Instead, implement class-specific versions ofinit... methods.

For historical reasons, alloc invokes allocWithZone:.

这里,主要看倒数第二行,我想原因应该是,alloc虽然初始化了,但是,我们并不可以复写它,而init则是可以复写的。在这里,如果有朋友有不同的解释和意见,希望可以在留言中提出。

刚才进入到了init方法,进一步证实了我的想法

An object isn’t ready to be used until it has been initialized. The init method defined in theNSObject class does no initialization; it simply returnsself.

In a custom implementation of this method, you must invoke super’s designated initializerthen initialize and return the new object. If the new object can’t be initialized, the method should returnnil.


2、在你自己的初始化方法中,需要调用自己的指定的初始化方法或者超累的指定初始化函数。一定要将超类的初始化函数的赋值给self对象,并返回你自己的初始化方法的值。超类可以决定,并返回一个完全不同的对象。

原创粉丝点击