Skip to content

Instantly share code, notes, and snippets.

@markd2
Created October 4, 2012 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markd2/3833834 to your computer and use it in GitHub Desktop.
Save markd2/3833834 to your computer and use it in GitHub Desktop.
Play with ARC variable lifetime qualifiers
#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