Search code examples
objective-calloc

Objective-C - difference between alloc and allocFromZone?


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;
}

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.