2015-10-11 1 views
0

J'essaie de maintenir un interne tableau de toutes les instances d'une classe donnée. Quand on est naturellement dérangé, il devrait être retiré de ce tableau statique.Comment gérer un tableau interne d'instances d'une classe?

Toutefois, dealloc ne sera jamais appelé si [instances addObject:weakSelf] est décommenté. Lorsque cela est mis en commentaire, les messages dealloc apparaissent normalement. Comment cela peut il etre accompli?

__weak MyClass *weakSelf; // A weak reference to myself 
static NSMutableArray *instances; 

- (instancetype)init { 
    self = [super init]; 
    if (self) { 
     if (!instances) { 
      instances = [[NSMutableArray alloc]init]; 
     } 
     weakSelf = self; 

     // Remember this instance 
     [instances addObject:weakSelf]; 
     NSLog(@"Instances count: %lu", (unsigned long)instances.count); 
    } 
    return self; 
} 

- (void)dealloc { 
    // Remove this instance from the array 
    [instances removeObject:weakSelf]; 
    NSLog(@"Instances count now: %lu", (unsigned long)instances.count); 
} 

+ (void)doSomething { 
    // enumerate the instances array and perform some action on each 
} 

Répondre

0

Vous devez créer un NSValue nonretain:

NSValue *value = [NSValue valueWithNonretainedObject:self]; 
[instances addObject:value]; 

Ref: NSArray of weak references (__unsafe_unretained) to objects under ARC

ou en utilisant "une catégorie qui fait NSMutableArray le cas échéant stocker des références faibles"

@implementation NSMutableArray (WeakReferences) 
    + (id)mutableArrayUsingWeakReferences { 
    return [self mutableArrayUsingWeakReferencesWithCapacity:0]; 
    } 

    + (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity { 
    CFArrayCallBacks callbacks = {0, NULL, NULL, CFCopyDescription, CFEqual}; 
    // We create a weak reference array 
    return (id)(CFArrayCreateMutable(0, capacity, &callbacks)); 
    } 
@end 

Ref: Non-retaining array for delegates

+0

Votre ref m'a mené dans la bonne direction (http://stackoverflow.com/a/4692229/4755085), donc j'ai fini par faire une catégorie sur NSMutableArray qui fonctionne bien. Merci. – Chan

+0

ok, je vais mettre à jour ma réponse – anhtu

+0

Pourquoi ne pas utiliser NSPointerArray? – Willeke