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

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

 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    CGRect fram=[UIScreen mainScreen].bounds; 
    UIView *testView=[[UIView alloc] initWithFrame:fram]; 
    testView.backgroundColor=[UIColor redColor]; 
    self.myView=testView; 
    [testView release]; 
 
     
} 
-(void)viewDidUnload 
{ 
    self.myView=nil; 
} 
-(void)dealloc 
{ 
    [myView release]; 
    [super dealloc]; 
} 

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

转:http://www.it165.net/pro/html/201302/4924.html

原文地址:https://www.cnblogs.com/ygm900/p/3127236.html