iOS全局变量变量与属性的内存管理

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

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

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