search

Home  >  Q&A  >  body text

ios - 为什么block 里面使用self,instruments leaks 没有检测出内存泄漏?需要用什么方法才能检测出

① 为什么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中文网2771 days ago635

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 09:46:06

    Using self in block is actually a circular reference, that is, there is a strong reference between the two objects compared to the ARC situation. Although neither of them releases the memory, they are both referenced. Currently, when using runtime debugging in Xcode 8, you can see the memory relationship diagram, and you can find the two objects that are circularly referenced through the relationship diagram.

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:46:06

    __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。
    
    

    reply
    0
  • Cancelreply