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;
}
@en开发者_JAVA百科d
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];
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.
精彩评论