2012-06-04 43 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发布];

在函数结束