2012-06-04 40 views
0

我是iPhone開發新手。如何釋放它?

+ (id<GMGridViewLayoutStrategy>)strategyFromType:(GMGridViewLayoutStrategyType)type 
{ 
    id<GMGridViewLayoutStrategy> strategy = nil; 

    switch (type) { 
     case GMGridViewLayoutVertical: 
      strategy = [[GMGridViewLayoutVerticalStrategy alloc] init]; 
      break; 
     case GMGridViewLayoutHorizontal: 
      strategy = [[GMGridViewLayoutHorizontalStrategy alloc] init]; 
      break; 
     case GMGridViewLayoutHorizontalPagedLTR: 
      strategy = [[GMGridViewLayoutHorizontalPagedLTRStrategy alloc] init]; 
      break; 
     case GMGridViewLayoutHorizontalPagedTTB: 
      strategy = [[GMGridViewLayoutHorizontalPagedTTBStrategy alloc] init]; 
      break; 
    } 

    return strategy; 
} 

在這裏,我調用一個方法:

gmGridView = [[GMGridView alloc] init]; 
gmGridView.layoutStrategy = [GMGridViewLayoutStrategyFactory strategyFromType:GMGridViewLayoutHorizontalPagedLTR]; 
[self.view addSubview:gmGridView]; 

現在我的問題是,如何釋放strategyFromType方法的戰略目標它給了我潛在的leak.and如果我打算髮布/自動釋放,我的應用程序崩潰了。 請幫助meThanking你...

+0

offtopic:你可以簡單地縮短[YourClass頁頭] INIT]到[YouClass新] – CarlJ

回答

4
return [strategy autorelease]; 

UPDATE:
有關返回一個autoreleased對象的答案是正確的,問題是GMGridView使用ARC根據在project's site描述。

要求:

的iOS 4和高達
的Xcode 4.2(GMGridView使用ARC)
框架:基金會 UIKit中,CoreGraphics中和QuartzCore

,所以我想你需要將其添加到項目作爲子模塊,但你可以搜索一些關於指令...

+0

每當我發佈/自動釋放該OBJ,應用程序崩潰。 – HML

+1

請確保您的layoutProperty屬性是使用retain聲明的:@property(retain,nonatomic)id layoutStrategy; –

+0

哦,讓我檢查.... – HML

0

當你返回對象時,你需要自動釋放對象

return [strategy autorelease]; 
1

如果您正在使用ARC那麼你的代碼是好的,但沒有ARC你應該返回一個自動釋放的對象:

+ (id)strategyFromType:(GMGridViewLayoutStrategyType)type { 
    id strategy = nil; 

    switch (type) { 
     case GMGridViewLayoutVertical: 
       strategy = [[GMGridViewLayoutVerticalStrategy alloc] init]; 
     break; 
     case GMGridViewLayoutHorizontal: 
      strategy = [[GMGridViewLayoutHorizontalStrategy alloc] init]; 
     break; 
     case GMGridViewLayoutHorizontalPagedLTR: 
      strategy = [[GMGridViewLayoutHorizontalPagedLTRStrategy alloc] init]; 
     break; 
     case GMGridViewLayoutHorizontalPagedTTB: 
      strategy = [[GMGridViewLayoutHorizontalPagedTTBStrategy alloc] init]; 
     break; 
    } 

    return [strategy autorelease]; 
} 

所有的對象都是通過方法的回報應該是autorelease,與異常,如果alloc,new和任何copy方法。

我真的建議閱讀Advanced Memory Management Programming Guide

0

return [strategy autorelease]; 也 [gmGridView發佈];

在函數結束