【问题标题】:How to maintain an internal array of instances of a class?如何维护类实例的内部数组?
【发布时间】:2015-10-11 05:00:10
【问题描述】:

我正在尝试维护给定类的所有实例的 internal 数组。当一个自然地被释放时,它应该从那个静态数组中删除。

但是,如果未注释 [instances addObject:weakSelf],则永远不会调用 dealloc。当它被注释掉时,dealloc 消息会正常显示。如何实现?

__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
}

【问题讨论】:

    标签: ios objective-c arrays static instances


    【解决方案1】:

    您应该创建一个NSValue nonretain:

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

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

    或者使用“使 NSMutableArray 可选择存储弱引用的类别”

    @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
    

    参考:Non-retaining array for delegates

    【讨论】:

    • 您的 ref 将我引向正确的方向 (stackoverflow.com/a/4692229/4755085),因此我最终在 NSMutableArray 上创建了一个运行良好的类别。谢谢。
    • 为什么不使用 NSPointerArray?
    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2012-05-22
    • 2012-04-03
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多