我有一个弱 NSPointerArray
,其中包含一些已经被释放的 NSObject
。在调用 compact
之前,我看到的是:
(lldb) po [currentArray count]
1
(lldb) po [currentArray pointerAtIndex:0]
<nil>
(lldb) po [currentArray allObjects]
<__NSArrayM 0x16f04f00>(
)
听起来很有道理,但真正奇怪的是,当我在那个数组上调用compact
时,我看到的值仍然相同!计数仍然返回1,而pointerAtIndex:0
是nil
。
为什么nil
没有被移除呢?
编辑
这是完整代码(是的,它是XCTest框架):
- (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
方法不删除第一个指针?在调用compact
之前,这显然是nil
。
NSObject
添加到指针数组中的?你是否正在使用weakObjectsPointerArray
? - Kazuki Sakamoto