代码之家  ›  专栏  ›  技术社区  ›  bitwit Julio Gorgé

目标C类方法控制所有现有实例?

  •  2
  • bitwit Julio Gorgé  · 技术社区  · 16 年前

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

    我希望一个委托类能够向对象的类方法发送消息,然后该类方法可以对外面的一切做出适当的反应。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Ed Marty    16 年前

    一定要使用一些对象集合。最简单的方法是将对象存储在一个数组中,并在需要发生某些事情时向它们发送一条消息。明确地:

    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];
        }
    }
    
        2
  •  3
  •   Chuck    16 年前

    当然。只需注册所有对象 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];
    }