what is difference between alloc and allocWithZone:?

Forrest picture Forrest · Dec 23, 2010 · Viewed 17.4k times · Source

From forum discussion , seem like that the big difference is performance factor, allocWithZone: will alloc memory from particular memory area, which reduce cost of swapping.

In practice, almost get no chance to use allocWithZone: , anyone can give simple example to illustrate which case to use allocWithZone: ?

Thanks,

Answer

d11wtq picture d11wtq · Dec 23, 2010

When one object creates another, it’s sometimes a good idea to make sure they’re both allocated from the same region of memory. The zone method (declared in the NSObject protocol) can be used for this purpose; it returns the zone where the receiver is located.

This suggests to me that your ivars, and any objects your classes "create" themselves could make use of +allocWithZone: in this way, to make the instances they create in the same zone.

-(id)init {
  if (self = [super init]) {
    someIvar = [[SomeOtherClass allocWithZone:[self zone]] init];
  }

  return self;
}