NSPointerArray奇怪的压缩

时间:2015-07-09 15:43:49

标签: objective-c automatic-ref-counting nspointerarray

我有一个弱NSPointerArray,其中一些NSObject已被释放。在致电compact之前,我看到的是:

(lldb) po [currentArray count]
1
(lldb) po [currentArray pointerAtIndex:0]
<nil>
(lldb) po [currentArray allObjects]
<__NSArrayM 0x16f04f00>(

)

这是有道理的,但真正奇怪的是,当我在该数组上调用compact时,我看到了相同的值!计数仍返回1,pointerAtIndex:0nil

为什么没有删除nil?

修改

这里是完整的代码(是的,它是XCTesting框架):

- (void)testCompaction {
    __weak id testingPointer = nil;

    NSPointerArray *weakArray = [NSPointerArray weakObjectsPointerArray];

    @autoreleasepool {

        NSObject *someObj = [[NSObject alloc] init];

        testingPointer = someObj;

        [weakArray addPointer:(__bridge void*)testingPointer];

        NSLog(@"before compaction inside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

        someObj = nil;
    }

    NSLog(@"before compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);

    [weakArray compact];

    NSLog(@"after compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);
}

和日志:

  before compaction inside autorelease: testingPointer = <NSObject: 0x7de7ff80> count = 1, allObjects = (
    "<NSObject: 0x7de7ff80>"
), pointerAtIndex:0 = <NSObject: 0x7de7ff80>, pointerAtIndex:0 class = NSObject
2015-07-20 14:27:14.062 AppetizeSuite copy[54144:9019054] before compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)
2015-07-20 14:27:22.615 AppetizeSuite copy[54144:9019054] after compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (
), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)   

为什么compact方法不会删除第一个指针?在致电nil之前,它显然是compact

3 个答案:

答案 0 :(得分:13)

发生这种情况的原因是-compact首先检查内部标志是否需要压缩&#39;已设定。如果不是,它只是提前保释。设置标志的唯一时间是nil指针是否通过公共接口直接插入到数组中。如果在将指针插入数组后释放弱引用对象(并且指针为nil&lt; d; d),则不会设置它。

解决此问题的一个方法是在调用-compact之前有目的地向数组附加一个nil指针。不理想,但它会起作用。

[pa addPointer:nil]; // forces the pointer array to do compaction next time
[pa compact];

答案 1 :(得分:2)

我已经看到了同样的行为。这是一个开放的雷达错误报告: http://www.openradar.me/15396578

答案 2 :(得分:0)

已经有几年了,使用示例代码显示没有变化。

但是,当使用-replacePointerAtIndex:withPointer方法执行指针更新时,-compact可以完美地工作:

在上面的代码中,替换

someObj = nil;

通过

 [weakArray replacePointerAtIndex:0 withPointer:nil];

提供[weakArray compact];之后的预期结果,并且代码将在最后一个NSLog崩溃