Can someone explain to me what init and alloc do in Obj-C. I am reading this obj-c book that gives an example of creating object but it does not really go into details of what it does. What does alloc return? what does init return?
有人可以向我解释一下init和alloc在Obj-C中做了什么。我正在阅读这本obj-c书,它提供了一个创建对象的例子,但它并没有详细说明它的作用。 alloc返回什么? init返回什么?
Animal * k = [Animal alloc];
k = [k init];
5 个解决方案
#1
35
-
alloc
allocates a chunk of memory to hold the object, and returns the pointer.alloc分配一块内存来保存对象,并返回指针。
MyClass* myObj = [MyClass alloc];
myObj
cannot be used yet, because its internal state is not correctly setup. So, don't write a code like this.myObj尚未使用,因为其内部状态未正确设置。所以,不要写这样的代码。
-
init
sets up the initial condition of the object and returns it. Note that what's returned by[a init]
might be different froma
. That explains the code Yannick wrote:init设置对象的初始条件并返回它。请注意,[init]返回的内容可能与a不同。这解释了Yannick写的代码:
-init{ self=[super init]; // 1. if(self){ // 2. .... } return self; // 3. }
- First, you need to call the superclass's
init
, to setup the superclass's instance variables, etc. That might return something not equal to the originalself
, so you need to assign what's returned toself
. - 首先,你需要调用超类的init,设置超类的实例变量等。这可能会返回不同于原始self的东西,所以你需要分配返回给self的内容。
- If
self
is non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set tonil
(if it's object) and0
if it's integer. You'll need to perform additional initial settings. - 如果self是非零的,则意味着由超类控制的部分被正确初始化。现在,您执行初始化。所有实例变量都设置为nil(如果是对象),如果是整数则设置为0。您需要执行其他初始设置。
- Return the set-up
self
. The returnedself
might be different from what's allocated! So, you need to assign the result ofinit
to your variable. - 返回设置自己。返回的自我可能与分配的不同!因此,您需要将init的结果分配给您的变量。
- First, you need to call the superclass's
This suggestions an important lesson: never split the call to alloc
and init
. Don't write:
这个建议是一个重要的教训:永远不要将调用拆分为alloc和init。不要写:
MyClass* myObj = [MyClass alloc];
[myObj init];
because [myObj init]
might return something else. Don't try to get around this by writing:
因为[myObj init]可能会返回其他内容。不要试图通过写:
MyClass* myObj = [MyClass alloc];
myObj=[myObj init];
because you will eventually forget to write the part myObj=
in the second line.
因为你最终会忘记在第二行写下myObj =部分。
Always write:
总是写:
MyClass* myObj = [[MyClass alloc] init];
I also don't recommend writing:
我也不建议写:
MyClass* myObj = [MyClass new];
because it does not correctly call the initialization method: some classes doesn't accept a plain init
. For example, NSView
needs initWithFrame:
, which can't be called with new
. So, don't use new
either.
因为它没有正确调用初始化方法:某些类不接受普通的init。例如,NSView需要initWithFrame:,无法使用new调用。所以,不要使用新的。
#2
3
In its simplest form:
最简单的形式:
-
alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable.
alloc:分配的缩写,重新存储内存位置并返回指向该内存位置的指针。然后将该指针存储在k变量中。
-
init: short for initialization, sets up the object and returns the object. The init method depends on the object, but it generally involves sending the init message to the superclass. And if that init method (of the superclass) returns an object (not nil) some ivars may be set up depending on the task of that class.
init:初始化的简称,设置对象并返回对象。 init方法依赖于对象,但它通常涉及将init消息发送到超类。如果那个(超类)的init方法返回一个对象(不是nil),可以根据该类的任务设置一些ivars。
--
-
Example of an init implementation, the Schedule class initializes its channels ivar with an empty array. Basically your giving the Schedule object a chance to sort itself out, so it can start receiving messages once it is created. You could remove the channels initialization from the init method, but then you would have to check if the channels ivar is nil in every method of the Schedule class and initialize it if it is indeed nil.
作为init实现的示例,Schedule类使用空数组初始化其通道ivar。基本上,您为Schedule对象提供了自我排序的机会,因此它可以在创建后开始接收消息。您可以从init方法中删除通道初始化,但是您必须检查Schedule类的每个方法中的通道ivar是否为nil,如果它确实为零则初始化它。
- (Schedule*)init {
self = [super init];
if (self) {
channels = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}
#3
1
alloc and init are two methods that are inherited from NSObject you can provide your own methods or call the ones from NSObject
alloc和init是从NSObject继承的两个方法,你可以提供自己的方法或从NSObject中调用它们
alloc allocates the memory to create a new instance of your class(@interface) init initializes the contents of that instance, by default init sets all member values to 0/nil however you can create your own init method to customize what is done.
alloc分配内存来创建类的新实例(@interface)init初始化该实例的内容,默认情况下,init将所有成员值设置为0 / nil,但是您可以创建自己的init方法来自定义完成的操作。
Animal * k = [[Animal alloc] init]; // creates a new Animal object
you can also write
你也可以写
Animal * k = [Animal new]; // which would be a bit more similar to other languages
#4
0
The NSObject root class provides a class method, alloc, alloc: reservers a memory location and returns the pointer to that memory location.
NSObject根类提供了一个类方法,alloc,alloc:reservers一个内存位置并返回指向该内存位置的指针。
The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero.
alloc方法还有另外一项重要任务,即通过将对象属性设置为零来清除为对象属性分配的内存。
This avoids the usual problem of memory containing garbage from whatever was stored before, but is
这避免了以前存储的包含垃圾的内存的常见问题,但是
not enough to initialize an object completely.
不足以完全初始化对象。
You need to combine a call to alloc with a call to init, another NSObject method:
你需要结合对alloc的调用和对init的调用,另一个NSObject方法:
-
(id)init; The init method is used by a class to make sure its properties have suitable initial values at creation. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:
(ID)初始化;类使用init方法来确保其属性在创建时具有合适的初始值。分配和初始化对象的正确方法是将alloc调用嵌套在init的调用中,如下所示:
ClassName *objectName = [ClassName alloc] init];
ClassName * objectName = [ClassName alloc] init];
from: apple documents
来自:苹果文件
#5
-1
Alloc will allocate the memory for the object, but Init puts the object into the memory and sets the default values.
Alloc将为对象分配内存,但Init将对象放入内存并设置默认值。
#1
35
-
alloc
allocates a chunk of memory to hold the object, and returns the pointer.alloc分配一块内存来保存对象,并返回指针。
MyClass* myObj = [MyClass alloc];
myObj
cannot be used yet, because its internal state is not correctly setup. So, don't write a code like this.myObj尚未使用,因为其内部状态未正确设置。所以,不要写这样的代码。
-
init
sets up the initial condition of the object and returns it. Note that what's returned by[a init]
might be different froma
. That explains the code Yannick wrote:init设置对象的初始条件并返回它。请注意,[init]返回的内容可能与a不同。这解释了Yannick写的代码:
-init{ self=[super init]; // 1. if(self){ // 2. .... } return self; // 3. }
- First, you need to call the superclass's
init
, to setup the superclass's instance variables, etc. That might return something not equal to the originalself
, so you need to assign what's returned toself
. - 首先,你需要调用超类的init,设置超类的实例变量等。这可能会返回不同于原始self的东西,所以你需要分配返回给self的内容。
- If
self
is non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set tonil
(if it's object) and0
if it's integer. You'll need to perform additional initial settings. - 如果self是非零的,则意味着由超类控制的部分被正确初始化。现在,您执行初始化。所有实例变量都设置为nil(如果是对象),如果是整数则设置为0。您需要执行其他初始设置。
- Return the set-up
self
. The returnedself
might be different from what's allocated! So, you need to assign the result ofinit
to your variable. - 返回设置自己。返回的自我可能与分配的不同!因此,您需要将init的结果分配给您的变量。
- First, you need to call the superclass's
This suggestions an important lesson: never split the call to alloc
and init
. Don't write:
这个建议是一个重要的教训:永远不要将调用拆分为alloc和init。不要写:
MyClass* myObj = [MyClass alloc];
[myObj init];
because [myObj init]
might return something else. Don't try to get around this by writing:
因为[myObj init]可能会返回其他内容。不要试图通过写:
MyClass* myObj = [MyClass alloc];
myObj=[myObj init];
because you will eventually forget to write the part myObj=
in the second line.
因为你最终会忘记在第二行写下myObj =部分。
Always write:
总是写:
MyClass* myObj = [[MyClass alloc] init];
I also don't recommend writing:
我也不建议写:
MyClass* myObj = [MyClass new];
because it does not correctly call the initialization method: some classes doesn't accept a plain init
. For example, NSView
needs initWithFrame:
, which can't be called with new
. So, don't use new
either.
因为它没有正确调用初始化方法:某些类不接受普通的init。例如,NSView需要initWithFrame:,无法使用new调用。所以,不要使用新的。
#2
3
In its simplest form:
最简单的形式:
-
alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable.
alloc:分配的缩写,重新存储内存位置并返回指向该内存位置的指针。然后将该指针存储在k变量中。
-
init: short for initialization, sets up the object and returns the object. The init method depends on the object, but it generally involves sending the init message to the superclass. And if that init method (of the superclass) returns an object (not nil) some ivars may be set up depending on the task of that class.
init:初始化的简称,设置对象并返回对象。 init方法依赖于对象,但它通常涉及将init消息发送到超类。如果那个(超类)的init方法返回一个对象(不是nil),可以根据该类的任务设置一些ivars。
--
-
Example of an init implementation, the Schedule class initializes its channels ivar with an empty array. Basically your giving the Schedule object a chance to sort itself out, so it can start receiving messages once it is created. You could remove the channels initialization from the init method, but then you would have to check if the channels ivar is nil in every method of the Schedule class and initialize it if it is indeed nil.
作为init实现的示例,Schedule类使用空数组初始化其通道ivar。基本上,您为Schedule对象提供了自我排序的机会,因此它可以在创建后开始接收消息。您可以从init方法中删除通道初始化,但是您必须检查Schedule类的每个方法中的通道ivar是否为nil,如果它确实为零则初始化它。
- (Schedule*)init {
self = [super init];
if (self) {
channels = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}
#3
1
alloc and init are two methods that are inherited from NSObject you can provide your own methods or call the ones from NSObject
alloc和init是从NSObject继承的两个方法,你可以提供自己的方法或从NSObject中调用它们
alloc allocates the memory to create a new instance of your class(@interface) init initializes the contents of that instance, by default init sets all member values to 0/nil however you can create your own init method to customize what is done.
alloc分配内存来创建类的新实例(@interface)init初始化该实例的内容,默认情况下,init将所有成员值设置为0 / nil,但是您可以创建自己的init方法来自定义完成的操作。
Animal * k = [[Animal alloc] init]; // creates a new Animal object
you can also write
你也可以写
Animal * k = [Animal new]; // which would be a bit more similar to other languages
#4
0
The NSObject root class provides a class method, alloc, alloc: reservers a memory location and returns the pointer to that memory location.
NSObject根类提供了一个类方法,alloc,alloc:reservers一个内存位置并返回指向该内存位置的指针。
The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero.
alloc方法还有另外一项重要任务,即通过将对象属性设置为零来清除为对象属性分配的内存。
This avoids the usual problem of memory containing garbage from whatever was stored before, but is
这避免了以前存储的包含垃圾的内存的常见问题,但是
not enough to initialize an object completely.
不足以完全初始化对象。
You need to combine a call to alloc with a call to init, another NSObject method:
你需要结合对alloc的调用和对init的调用,另一个NSObject方法:
-
(id)init; The init method is used by a class to make sure its properties have suitable initial values at creation. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:
(ID)初始化;类使用init方法来确保其属性在创建时具有合适的初始值。分配和初始化对象的正确方法是将alloc调用嵌套在init的调用中,如下所示:
ClassName *objectName = [ClassName alloc] init];
ClassName * objectName = [ClassName alloc] init];
from: apple documents
来自:苹果文件
#5
-1
Alloc will allocate the memory for the object, but Init puts the object into the memory and sets the default values.
Alloc将为对象分配内存,但Init将对象放入内存并设置默认值。