1

ARC では、すべてのインスタンス変数とローカル変数は、デフォルトで、それらが指しているオブジェクトへの強い参照を持っています。MRR がどのように機能するかを理解しようとしており、この例に出くわしました。以下のスニペットを検討してください。

// CarStore.h #import

@interface CarStore : NSObject

- (NSMutableArray *)inventory;
- (void)setInventory:(NSMutableArray *)newInventory;

@end

// CarStore.m
#import "CarStore.h"

@implementation CarStore {
    NSMutableArray *_inventory;
}

- (NSMutableArray *)inventory {
    return _inventory;
}

- (void)setInventory:(NSMutableArray *)newInventory {
    _inventory = newInventory;
}

@end

// main.m に戻り、在庫変数を作成して CarStore の在庫プロパティに割り当てましょう。 int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *inventory = [[NSMutableArray alloc] init]; [inventory addObject:@"Honda Civic"];

        CarStore *superstore = [[CarStore alloc] init];
        [superstore setInventory:inventory];
        [inventory release];

        // Do some other stuff...

        // Try to access the property later on (error!)
        NSLog(@"%@", [superstore inventory]); //DANGLING POINTER
    }
    return 0;
}

main メソッドの最後の行にあるインベントリ プロパティは、オブジェクトが main.m で既に解放されているため、ダングリング ポインターです。現在、スーパーストア オブジェクトには配列への弱い参照があります。

これは、ARC 以前は、インスタンス変数はデフォルトで弱い参照を持っていたので、retain を使用して強い参照を要求する必要があったということですか?

4

1 に答える 1

0

ARC の前は、デフォルトで __unsafe_unretained でした。Weak は ARC とともに導入されました。

于 2013-08-17T17:18:10.660 に答える