Created
October 4, 2012 14:25
-
-
Save markd2/3833834 to your computer and use it in GitHub Desktop.
Play with ARC variable lifetime qualifiers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
// clang -g -fobjc-arc -Wall -framework Foundation -o unsafe unsafe.m | |
@interface NSThing : NSObject | |
@end | |
@implementation NSThing | |
- (void) dealloc { | |
NSLog (@"dealloc called for thing %p", self); | |
} // dealloc | |
@end // NSThing | |
int main (void) { | |
{ | |
NSLog (@"Regular strong reference"); | |
NSThing *thisThing = [[NSThing alloc] init]; | |
NSThing *thatThing = thisThing; | |
thisThing = nil; | |
NSLog (@"that thing is %@", thatThing); | |
} | |
{ | |
NSLog (@"Regular weak reference"); | |
NSThing *thisThing = [[NSThing alloc] init]; | |
__weak NSThing *thatThing = thisThing; | |
thisThing = nil; | |
NSLog (@"that thing is %@", thatThing); | |
} | |
{ | |
NSLog (@"Unretained-unreleased reference"); | |
NSThing *thisThing = [[NSThing alloc] init]; | |
__unsafe_unretained NSThing *thatThing = thisThing; | |
thisThing = nil; | |
NSLog (@"that thing is %@", thatThing); | |
} | |
#if BAD_PROGRAMMER_NO_COOKIE | |
struct StructWithObject { | |
NSThing *otherThing; // ARC forbids Objective-C objects in structs or unions | |
}; | |
#else | |
struct StructWithObject { | |
__unsafe_unretained NSThing *otherThing; | |
}; | |
#endif | |
return 0; | |
} // main | |
#if 0 | |
% ./unsafe | |
unsafe[44029:303] Regular strong reference | |
unsafe[44029:303] that thing is <NSThing: 0x7f9b93500340> | |
unsafe[44029:303] dealloc called for thing 0x7f9b93500340 | |
unsafe[44029:303] Regular weak reference | |
unsafe[44029:303] dealloc called for thing 0x7f9b95000020 | |
unsafe[44029:303] that thing is (null) | |
unsafe[44029:303] Unretained-unreleased reference | |
unsafe[44029:303] dealloc called for thing 0x7f9b95000020 | |
unsafe[44029:303] that thing is <NSThing: 0x7f9b95000020> | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment