ios - 为什么block 里面使用self,instruments leaks 没有检测出内存泄漏?需要用什么方法才能检测出
PHP中文网
PHP中文网 2017-04-18 09:44:06
0
2
597

① 为什么block 里面使用self,instruments leaks 没有检测出内存泄漏?
② 那么需要用什么方法才能检测出这里是出现了内存泄漏,因为一直都是网上这么说的,自己检测就不出来了。

下面事例代码:


#import "ViewController.h"

typedef void(^myBlock)(NSString *);

@interface ViewController ()

@property(nonatomic, copy) myBlock BlockName;

@property (nonatomic, copy) NSString  *name1;
@property (nonatomic, copy) NSString  *name2;
@property (nonatomic, strong) NSMutableArray  *students;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /// 问:为什么instruments leaks 没有检测出内存泄漏?
    /// 那么需要用什么方法才能检测出这里是出现了内存泄漏,因为一直都是网上这么说的,自己检测就不出来了。
    self.BlockName = ^(NSString *ken){
        self.name1 = ken;
        self.name2 = ken;
        [self.students addObject:self.name1];
        [self.students addObject:self.name2];
    };
    
    self.BlockName(@"apple");
}

@end
PHP中文网
PHP中文网

认证高级PHP讲师

Antworte allen(2)
大家讲道理

在block使用self实际上是循环引用,也就是相对于ARC情况下两个对象之间进行了强引用,虽然彼此都没有释放内存,但是彼此都是被引用者。目前Xcode 8中使用runtime调试可以看到内存的关系图,可以通过关系图找到循环引用的两个对象。

黄舟
__weak __typeof(self) weakSelf=self;
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 6ull * NSEC_PER_SEC);
    NSLog(@"waited at least 6s.");
    dispatch_after(time, dispatch_get_main_queue(), ^{
        __strong __typeof(weakSelf) strongSelf=weakSelf;
        if (strongSelf) {
            NSLog(@"Oh,shit. self is not nil");
        }else
        {
            NSLog(@"Congratulations");
        }

    });
    
将上段代码放在viewDidLoad里面即可。push这个vc,6秒内pop掉,等待log。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!