开发者

Objective C Class Method to control all existing instances?

Is it possible to use the class methods of some NSObject I've made to controls all existing i开发者_开发技巧nstances?

I want a delegate class to be able to send messages to the Object's class methods which can then react appropriately with everything out there.


Sure. Just have all the objects register for notifications when they're created. For example:

- (id)init {
    self = [super init];
    if (!self) return nil;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(announceYourself:)
                                                 name:@"MYCLASS_ANNOUNCE"
                                               object:nil];
    return self;
}

+ (void)identifyInstances {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MYCLASS_ANNOUNCE" object:self];
}

- (void)announceYourself:(id)notification {
    NSLog(@"Instance %p reporting in!", self);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self]; // VERY IMPORTANT -- IT WILL CRASH WITHOUT THIS
    [super dealloc];
}


Not without using some collection of the objects. The simplest way to do it would be to store the objects in an array and send them all a message when you want something to happen. Specifically:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜