iOS全域性變數與屬性的記憶體管理

weixin_33816946發表於2013-06-08
在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

相關文章