For*_*est 50 memory-management objective-c alloc
从论坛讨论看,似乎最大的区别是性能因素,allocWithZone:将从特定的内存区域分配内存,从而降低交换成本.
在实践中,几乎没有机会使用allocWithZone:,任何人都可以给出一个简单的例子来说明使用allocWithZone的情况:
谢谢,
d11*_*wtq 47
当一个对象创建另一个对象时,确保它们都是从相同的内存区域分配有时是个好主意.zone方法(在NSObject协议中声明)可用于此目的; 它返回接收器所在的区域.
这告诉我,你的ivars,以及你的类"创建"自己的任何对象都可以通过+allocWithZone:这种方式使用它们来创建它们在同一区域中创建的实例.
-(id)init {
if (self = [super init]) {
someIvar = [[SomeOtherClass allocWithZone:[self zone]] init];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
使用allocWithZone的一个很好的例子是当你实现NSCopy协议时,它允许你使自定义对象可以复制(深度复制/按值复制),如:
(1) ClassName *newObject = [currentObject copy]; //results in newObject being a copy of currentObject not just a reference to it
Run Code Online (Sandbox Code Playgroud)
NSCopy协议确保您实现一个方法:
(2) -(id)copyWithZone:(NSZone *)zone;
Run Code Online (Sandbox Code Playgroud)
复制对象时,如上所述发送的"复制"消息(1),当声明为'copyWithZone时,向方法(2)发送消息.也就是说你不需要做任何事来自己获得一个区域.
现在,当您向此消息发送"区域"时,您可以使用它来确保从与原始内容相同的区域中的内存进行复制.
这可以像:
-(id)copyWithZone:(NSZone *)zone
{
newCopy = [[[self class]allocWithZone:zone]init]; //gets the class of this object then allocates a new object close to this one and initialises it before returning
return(newCopy);
}
Run Code Online (Sandbox Code Playgroud)
这是我唯一知道allocWithZone实际使用的地方.