联系客服:400-805-1963

iOS全局变量变量与属性的内存管理
更新:HHH   时间:2023-1-7


在iOS开发中,为了节约时间,程序员经常会用全局变量代替属性。但是这样做,尤其是新手开发中,经常会引起内存泄露的报错,其实作为苹果自己也没有给出一个完美安全的内存管理代码例子。但是在iOS开发到如今,有一个相对比较安全的内存管理模版。

  1. - (void)viewDidLoad 
  2. { 
  3.     [super viewDidLoad]; 
  4.     // Do any additional setup after loading the view, typically from a nib. 
  5.     CGRect fram=[UIScreen mainScreen].bounds; 
  6.     UIView *testView=[[UIView alloc] initWithFrame:fram]; 
  7.     testView.backgroundColor=[UIColor redColor]; 
  8.     self.myView=testView; 
  9.     [testView release]; 
  10.  
  11.      
  12. } 
  13. -(void)viewDidUnload 
  14. { 
  15.     self.myView=nil; 
  16. } 
  17. -(void)dealloc 
  18. { 
  19.     [myView release]; 
  20.     [super dealloc]; 
  21. } 

原理比较简单,首先我们简历临时变量,alloc临时的后,把临时变量的值赋给属性的,然后把临时的release掉,
这样,属性,只需要在dealloc中写一个release就可以了!

返回移动开发教程...