Objective C Class控制所有现有实例的方法?

时间:2010-05-27 22:16:25

标签: objective-c

是否可以使用我所做的某些NSObject的类方法来控制所有现有的实例?

我希望委托类能够向Object的类方法发送消息,然后可以对所有内容做出适当的反应。

2 个答案:

答案 0 :(得分:3)

不确定。只需让所有对象在创建时注册notifications。例如:

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

答案 1 :(得分:2)

不使用某些对象集合。最简单的方法是将对象存储在一个数组中,并在需要发生时向它们发送所有消息。具体做法是:

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