views:

48

answers:

1

Hi! 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];
+3  A: 

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.

Graham Lee
Zones are effectively deprecated and should be entirely ignored.
bbum
@bbum: is that deprecation documented?
Graham Lee
bbum