Question

Possible Duplicate:
what is difference between alloc and allocWithZone:?

I read an article that mentions using allocWithZone helps improve performance by using a memory location closer to the object itself. Is this true? and is it recommended to use allocWithZone instead of alloc? What is the difference between alloc and allocWithZone?

The example proveded was:

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

   return self;
}
Was it helpful?

Solution

First ARC disallows calling zone on objects. Since all things are moving that way that seems a good enough reason to not use allocWithZone.

There is one good use that I know of to use allocWithZone, conforming to NSCopying.

@protocol NSCopying
- (id)copyWithZone:(NSZone *)zone;
@end

And while you can ignore the zone parameter alltogether, I like to do something like:

-(id)copyWithZone:(NSZone *)zone{
    SampleClass *copy = [[SampleClass allocWithZone:zone] init];
    copy->_myString = [_myString copyWithZone:zone];
    return copy;
}

Other than that I don't think there's much more to say than is posted the previous question.

OTHER TIPS

Straight from the horse's mouth:

There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway

(That's from the ARC release notes, for anyone reading this after Apple breaks their documentation structure again.)

Memory zones were somewhat useful once upon a time, but Cocoa has pretty thoroughly moved away from them. NSZone is like a vestigial tail, and both ARC and the libauto GC cut it off. As Apple engineer Bill Bumgarner pointed out in the comments on bryanmac's dupe, they were simply unwieldy and not used to great effect in Cocoa.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top