考虑一下这段代码:
@implementation MyClass
-(void)dealloc {
NSLog(@"MyClass dealloc: %@", self);
}
@end
@implementation AppDelegate
__weak static MyClass *weakShared = nil;
- (MyClass *)getMyClass {
MyClass *tmpHolder = [[MyClass alloc] init]; // PREPEND "__autoreleasing"
weakShared = tmpHolder;
return weakShared; // ATTENTION TO THIS LINE
}
- (void)logMyClass:(NSUInteger)i {
MyClass *mc = [self getMyClass];
NSLog(@"(%@) this is MyClass: %@", @(i), mc);
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
@autoreleasepool {
for (int i = 0; i < 10; i++) {
[self logMyClass:i];
}
NSLog(@"end");
} …Run Code Online (Sandbox Code Playgroud) macos memory-management objective-c ios automatic-ref-counting