探索子线程autorelease对象的释放时机

前言

今天在给同事讲autorelease对象释放时机:

1.手动添加的autoreleasepool,pool release或者drain的时候释放
MRC下

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init;
// xxxxx
[pool drain];

ARC下

@autoreleasepool {
}

2.runloop循环释放
runloop循环中创建新的autoreleasepool并在循环结束中释放

autorelease原理在黑幕背后的Autorelease有详细的介绍
runloop原理可以参考深入理解RunLoop

但一个子线程,默认是没有runloop的(第一次获得runloop对象时候创建),如果子线程上的autorelease对象何时释放?

猜测
* 子线程执行完任务被释放

实例测试

测试:一个网上很多很多的例子(自己也写了一遍)

//
//  ViewController.m
//  Test
//
//  Created by game3108 on 16/3/14.
//  Copyright © 2016年 game3108. All rights reserved.
//

#import "ViewController.h"
#import "TestObject.h"

@interface ViewController (){
   
    __weak id _testObject;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    TestObject *testObject = [TestObject instanceWithNumber:10];
    _testObject = testObject;

    UIButton *test = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    test.backgroundColor = [UIColor blackColor];
    [self.view addSubview:test];
    [test addTarget:self action:@selector(testButton) forControlEvents:UIControlEventTouchUpInside];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear : %@", _testObject);
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"viewDidAppear : %@", _testObject);
}

- (void)testButton{
    NSLog(@"testButton : %@", _testObject);
}
//
//  TestObject.h
//  Test
//
//  Created by game3108 on 16/4/5.
//  Copyright © 2016年 game3108. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TestObject : NSObject

+ (instancetype) instanceWithNumber:(NSInteger)number;

@end
//
//  TestObject.m
//  Test
//
//  Created by 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值