一定要使用一些对象集合。最简单的方法是将对象存储在一个数组中,并在需要发生某些事情时向它们发送一条消息。明确地:
static NSMutableArray *allObjects = nil;
+ (void) initialize {
if (!allObjects) {
allObjects = [NSMutableArray new];
}
}
- (id) init {
if (self = [super init]) {
//Each object gets held in an array
[allObjects addObject:self];
}
return self;
}
+ (void) doSomethingToEveryObject {
[allObjects makeObjectsPerformSelector:@selector(doSomethingToThisObject)];
}
- (void) doSomethingToThisObject {
NSLog(@"Did something to %@",self];
}
- (void) release {
[super release];
//When the retain count reaches 1, then all external references have disappeared,
//and the only remaining reference is in the objects array.
if (self.retainCount == 1) {
[allObjects removeObject:self];
}
}