Automatic Reference Counting

Tested __strong, __weak and __unsafe_unretained.
__weak reference becomes nil when the target is dealloced, __unsafe_unretained becomes a dangling pointer.

Test Result:
1. Alloc -> Print

2012-06-14 23:49:08.286 ArcSpike[1561:403] strong: <NSObject: 0x7f8813b225c0>
2012-06-14 23:49:08.287 ArcSpike[1561:403] weak:   <NSObject: 0x7f8813b225c0>
2012-06-14 23:49:08.287 ArcSpike[1561:403] unsafe: <NSObject: 0x7f8813b225c0>

2. Alloc -> Free -> Print

2012-06-14 23:49:09.253 ArcSpike[1561:403] strong: (null)
2012-06-14 23:49:09.254 ArcSpike[1561:403] weak:   (null)
2012-06-14 23:49:09.255 ArcSpike[1561:403] unsafe: <NSObject: 0x7f8813b225c0>

or, causes access violation when referencing unsafeReference in print.

Test Code:

@interface WindowController : NSWindowController
{
id __strong strongReference;
id __weak weakReference;
id __unsafe_unretained unsafeReference;
}

- (IBAction)testAlloc:(id)sender;
- (IBAction)testFree:(id)sender;
- (IBAction)print:(id)sender;

@end

@implementation WindowController
...

- (IBAction)testAlloc:(id)sender
{
strongReference = [[NSObject alloc] init];
weakReference = strongReference;
unsafeReference = strongReference;
}

- (IBAction)testFree:(id)sender
{
strongReference = nil;
}

- (IBAction)print:(id)sender
{
NSLog(@"strong: %@", strongReference);
NSLog(@"weak: %@", weakReference);
NSLog(@"unsafe: %@", unsafeReference);
}
@end

Leave a Reply

Your email address will not be published. Required fields are marked *