iOS开发-对象什么时候dealloc?dealloc发生在哪个线程?

1、对象什么时候dealloc?

当对象的引用计数减为0时候。

2、dealloc发生在哪个线程?


#import "ViewController.h"

@interface classTest : NSObject

@end

@implementation classTest

- (void)dealloc{
    
    NSThread *currentThread = [NSThread currentThread];
    NSLog(@"object dealloc at thread: %@",currentThread);
}

@end

@interface ViewController ()
@property(nonatomic,strong) NSMutableArray *tArr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self dealloc_test];
}


-(void)dealloc_test{
    _tArr = [NSMutableArray array];
    NSThread *currentThread = [NSThread currentThread];
    NSLog(@"viewDidLoad at thread: %@",currentThread);
    
    classTest *t = [[classTest alloc]init];
    [_tArr addObject:t];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSThread currentThread] setName:@"DISPATCH_QUEUE_XXX"];
        [self.tArr removeAllObjects];
    });
}

执行结果:

2019-07-11  xxtest[29479:1344125] viewDidLoad at thread: {number = 1, name = main}
2019-07-11  xxtest[29479:1344218] object dealloc at thread: {number = 3, name = DISPATCH_QUEUE_XXX}

dealloc并不总是在主线程中被调用,,其调用线程为最后一个调用release方法的线程。
也就是说,dealloc方法有可能在任何线程被调用。

你可能感兴趣的:(iOS开发-对象什么时候dealloc?dealloc发生在哪个线程?)