简体   繁体   中英

When is the autorelease object released?

I tested it with the following code,and I found that the autorelease objc never release.

__weak id ref;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *str = [NSString stringWithFormat:@"test"]; // add autoreleasePool
    ref = str;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear:%@",ref); // result test
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"viewDidAppear:%@",ref); // result test
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%@",ref); // If I click long after,But it has not been released
}

[NSString stringWithFormat:] doesn't promise you an object on the autoreleasepool. It promises you an object that you do not have to release. In this case, it's returning you a constant string, and a constant string is never destroyed. It is also free to return you a cached value, or a value shared with other readers, a tagged pointer, or a singleton. NSNumber has lots of optimizations like this.

To the underlying question, when the local autorelease pool is drained, one release will be sent to the object for each autorelease that was previously sent to the object on that pool. Whether this destroys the object or not depends on what other retains have been placed on it.

I would expect a value like this to behave closer to what you're expecting, but there are no promises:

[NSString stringWithFormat:@"something a little long and computed: %d", rand()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM