iOS 开发 Objective-C

iOS 底层 day29 循环引用 和 内存泄露

2020-10-14  本文已影响0人  望穿秋水小作坊

一、UIView 的 block 写动画

1. 请问下面代码有内存泄露吗?有循环引用吗?
// 情况一
@implementation UIViewAnimationsBlock
- (void)viewDidLoad {
    [super viewDidLoad];
    NSTimeInterval duration = 1000;
    [UIView animateWithDuration:duration animations:^{
        [self.view.superview layoutIfNeeded];
    }];
}
- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
2. UIViewblock 写动画时不需要考虑循环引用的原因是?

二、NSNotificationCenter 的 block 使用

1. 请问下面代码有内存泄露吗?有循环引用吗?
// 情况二
@implementation NSNotificationCenterBlock
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"someNotification"
                           object:nil
                           queue:[NSOperationQueue mainQueue]
                       usingBlock:^(NSNotification * notification) {
        NSLog(@"%@", self);
    }];
}
- (void)remove {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc {
    [self remove];
    NSLog(@"%s", __func__);
}
@end
2. 情况二解析
3. 请问下面代码有内存泄露吗?有循环引用吗?
// 情况三
@interface NSNotificationCenterIVARBlock ()
@property (nonatomic, strong) id observer;
@end
@implementation NSNotificationCenterIVARBlock
- (void)viewDidLoad {
    [super viewDidLoad];
    self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"testKey"
                                                                         object:nil
                                                                          queue:nil
                                                                     usingBlock:^(NSNotification *note) {
                                                                         NSLog(@"%@", self);
    }];
}
- (void)remove {
    [[NSNotificationCenter defaultCenter] removeObserver:self.observer];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self remove];
}
- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
4. 情况三解析
5. 如何利用 Xcode 检查情况三存在的内存泄露和循环引用?
leaks 查看NSNotificationCenterIVARBlock 内存泄露图 循环引用结构

三、GCD 和 NSOperationQueue 的 block 使用

1. 请问下面代码有内存泄露吗?有循环引用吗?
// 情况四
@interface GCDBlock ()
@property(nonatomic, strong) dispatch_queue_t myQueue;
@end

@implementation GCDBlock
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(self.myQueue, ^{
        [self doSomething];
    });
}
- (void)doSomething {
    NSLog(@"%s", __func__);
}
- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
2. 请问下面代码有内存泄露吗?有循环引用吗?
// 情况五
@implementation NSOperationQueueBlock
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ NSLog(@"%@",self); }];
}
- (void)dealloc {
    NSLog(@"%s", __func__);
}
@end
3. 情况四 情况五解析
上一篇 下一篇

猜你喜欢

热点阅读