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

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ハッシュマップが実際に空であり、強い参照が破棄されるループ内でオブジェクトが正しく破棄されることがわかるはずです。しかし、問題は.countプロパティにあります。それは嘘をつき、何もallObjects返さないにもかかわらずエントリがあることを伝えています。

于 2017-01-25T10:36:01.667 に答える
0

ドキュメントが言ったように:

主なオプションは、自動的に削除される「弱い」参照を提供することですが、将来の不確定な時点で削除されます。

なので、自動削除のポイントが不明で、次の実行ループで削除される保証もないので、あてにできませんAutoReleasePool

于 2017-09-14T06:33:52.523 に答える