1

In Cocoa Fundametals I found following code:

@interface ValidatingArray : NSMutableArray {
   NSMutableArray *embeddedArray;
}
@end

@implementation ValidatingArray
- init {
 self = [super init];
 if (self) {
   embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init];

   return self;
}
@end

But I don't understand this line of code:

embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init];

Why we use this initialization instead of simple memory allocation:

embeddedArray = [[NSMutableArray alloc] init];

1 Answer 1

3

Memory zones in Cocoa are used to put related objects into close proximity in memory, to try and reduce the number of page faults needed to bring an object and the things it uses out of swap. The object being initialised in -init may have been created in a custom zone using +allocWithZone:, so -init tries to put its ivar objects into the same zone to honour the meaning of the zones.

In practice this is defending against a case that comes up very rarely. I remember seeing code that used custom zones in OpenStep, but have never needed to use zones myself.

Sign up to request clarification or add additional context in comments.

4 Comments

Zones are effectively deprecated and should be entirely ignored.
@bbum: is that deprecation documented?
Not really. You can still use zones for stuff, but the use is limited. Mixing zones with Foundation & trying to do bulk deallocation (most of the point of zones) is a recipe for disaster.
In Apple's Transitioning to ARC Release Notes it is stated, "You cannot use memory zones; There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.