在ARC下的内存优化<一>

 

1.前言  

     原本觉得在改为ARC之后,再也不须要考虑内存问题了,但是在实践中仍是发现有一些内存问题须要注意,今天我不谈block的循环引用的问题,主要说说一些对象、数组不内存得不到释放的状况.  数组

2.数组内存得不到释放的状况  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//组织字典数据
- (NSMutableDictionary *)setupDicData{
   
     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
     for ( int i = 0; i <= 30; i++) {
       
         [dict setObject:[self setupArrayData] forKey:[NSString stringWithFormat: @"%d%@" ,i, @"class" ]];
     }
     return dict;
}
 
//组织数组数据
- (NSMutableArray *)setupArrayData{
   
     NSMutableArray *marry = [NSMutableArray array];
   
     for ( int i = 0; i<=30; i++) {
       
         NSString *s = [NSString stringWithFormat: @"%@" , @"data-test" ];
       
         [marry addObject:s];
       
     }
     return marry;
}

 运行+——oop

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- ( void )viewDidLoad {
   
     [super viewDidLoad];
   
   
     while ( true ) {
       
         //30.0定时执行
       
         [NSThread sleepForTimeInterval:30.0];
       
         NSDictionary *dict = [self setupDicData];
       
         NSLog( @"%@" ,dict);
         //每次数据内存都得不到释放
 
     }
}

 

  //按上代码传递数组执行,每次数组、对象内存都得不到释放。如图:内存会无线的往上增长,直至崩溃。    spa

2.是什么缘由致使这种内存得不到释放的?  

  主要是你在iOS里使用    while (true) {} 无线循环时, iOS ARC默认认为你这个方法永远没有执行完,因此不会去主动释放你方法里的对象,这一点和JAVA不同, 因此不少JAVA开发者转iOS后习惯性的使用while(true){} 致使项目里存在这种内存隐患,致使内存无限增长。code

 

3.如何解决这种数组传递内存得不到释放的状况?  

解决方法一:orm

3.1.最简单最直接在ARC的环境下使用        @autoreleasepool {}  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//@autoreleasepool {}的做用是在每次循环一次,都会把内存主动释放掉
 
 
- ( void )viewDidLoad {
    
     [super viewDidLoad];
    
    
     while ( true ) {
       
         @autoreleasepool {
             //30.0定时执行
            
             [NSThread sleepForTimeInterval:30.0];
            
             NSDictionary *dict = [self setupDicData];
            
             NSLog( @"%@" ,dict);
             //每次数据内存都得不到释放
         }
     }
}

 

 内存图,咱们发现很稳定,每次都会主动将内存释放    解决方法二:对象

3.2.使用NSTimer来作数组传递的无限循环,ARC会自动帮你释放内存  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- ( void )usingDatadosomething{
   
     //30.0定时执行
   
     [NSThread sleepForTimeInterval:0.10];
   
     NSDictionary *dict = [self setupDicData];
   
     NSLog( @"%@" ,dict);
     //每次数据内存都得不到释放
 
}
 
 
 
- ( void )viewDidLoad {
   
     [super viewDidLoad];
   
     [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(usingDatadosomething) userInfo:self repeats:YES];
   
     [[NSRunLoop currentRunLoop] run];
   
}

 内存图以下内存

 

解决方法三:ci

3.3.使用block封装数组传递,最后作block的释放,ARC会自动帮你释放内存  

相关文章
相关标签/搜索