3

我试图了解 ARC 和 NSHashTable weakObjectsHashTable 的工作原理。我添加到哈希表的对象应该被删除/归零,或者一旦对象被释放,它们就会变成任何东西。下面的 NSLog 中的代码示例显示该对象仍然存在于哈希表中。我究竟做错了什么?

#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];

        @autoreleasepool
        {
            NSString *str = @"Hello World!";
            [hashTable addObject:str];
            str = nil;
        }

        NSLog(@"hashTable:%@", [hashTable allObjects]);
        // prints: hashTable:("Hello World!") – but should be empty?
    }
}
4

3 回答 3

1

分配 nil 对象不会影响结果。NSString *str = @"Hello World!"; 对象引用不弱!苹果的文件说:如果在这样的哈希表中没有对对象的强引用,这些对象就会被释放。

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Collections/Articles/Sets.html#//apple_ref/doc/uid/20000136-CJBDHAJD

于 2015-05-11T00:44:43.693 回答
1

试试 OS X 控制台应用程序的这段代码:

//
//  main.m
//  

#import <Foundation/Foundation.h>

uint objectsAlive = 0;
uint totalObjects = 0;

@interface TestObject : NSObject
@end

@implementation TestObject
{
    uint myIx;
}

- (id)init
{
    // NSAssert([NSThread currentThread] == [NSThread mainThread], @"Not on the main thread");

    self = [super init];
    if (self)
    {
        objectsAlive++;
        totalObjects++;

        myIx = totalObjects;

        NSLog(@"Object with id=%u created; alive objects %u", myIx, objectsAlive);
    }

    return self;
}

- (void)dealloc
{
    objectsAlive--;
    NSLog(@"Object  with id=%u is being destroyed by ARC; alive objects will become %u", myIx,objectsAlive);
}

@end

int main(int argc, const char * argv[]) {

    // default global autorelease pool
    @autoreleasepool {

        NSHashTable * testHashMap = [NSHashTable weakObjectsHashTable];
        // weakObjectsHashTable - according to Apple docs, entries are not necessarily purged right away when the weak object is reclaimed, and we can observe this behavior here - some entries stay alive until last autorelease

        // comment out the line above and uncomment the line below to observe different behavior with strong references in NSHashTable
        // NSHashTable * testHashMap = [[NSHashTable alloc] init];

        // nested autoreleasepool to ensure that the objects added to the testHashMap are released by ARC
        @autoreleasepool {

            for(int i = 0; i < 10;i++) {
                TestObject * obj = [[TestObject alloc] init];
                [testHashMap addObject: obj];
                NSLog(@"Count in hash table inside additions scope is %lu",
                      (unsigned long)testHashMap.count);
            }

            NSLog(@"Count in hash table inside @autoreleasepool is %lu",
                  (unsigned long)testHashMap.count);
            NSLog(@"Objects in hash table inside of @autoreleasepool are %@",
                  testHashMap.allObjects);
            NSLog(@"Exiting inner autorelease pool...");

        }

        // objects in NSHashTable also were released, according to dealloc logs in TestObject, but count is still lagging behind (shows 2)
        NSLog(@"Count in hash table outside of @autoreleasepool is %lu",
              (unsigned long)testHashMap.count);

        // this should indeed show that NSHashTable with weakObjectsHashTable is empty, despite count=2
        NSLog(@"Objects in hash table outside of @autoreleasepool are %@",
              testHashMap.allObjects);

        NSLog(@"Exiting outer autorelease pool, ecpect all objects in strong ref NSHashTable to die...");
    }

    return 0;
}

for您应该看到 hashmap 确实是空的,并且对象在其强引用被丢弃的循环内被正确销毁。但问题出在.count属性上——它在说有条目,但allObjects没有返回。

于 2017-01-25T10:36:01.667 回答
0

正如文件所说:

主要选项是提供自动删除的“弱”引用,但在未来某个不确定的时间点。

所以,自动移除的点是未知的,也不能保证在下一次运行循环中会被移除,所以不能依赖AutoReleasePool.

于 2017-09-14T06:33:52.523 回答