gpt4 book ai didi

objective-c - NSPointerArray 奇怪的压缩

转载 作者:太空狗 更新时间:2023-10-30 03:21:54 25 4
gpt4 key购买 nike

我有一个弱 NSPointerArray 和一些已发布的 NSObject。在调用 compact 之前,我看到的是:

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

)

这是有道理的,但真正奇怪的是,当我对该数组调用 compact 时,我看到了相同的值! Count 仍然返回 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 方法不删除第一个指针?在调用 compact 之前,它显然是一个 nil

最佳答案

发生这种情况的原因是 -compact 首先检查是否设置了内部标志“needsCompaction”。如果不是,它就会提前退出。设置标志的唯一时间是通过公共(public)接口(interface)将 nil 指针直接插入到数组中。如果在将指针插入数组后释放弱引用对象(并且指针为 nil),则不会设置它。

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

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

关于objective-c - NSPointerArray 奇怪的压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com