怎么发布呢?

时间:2012-06-04 09:56:20

标签: iphone

我是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方法的策略对象?它给我潜在的泄漏。如果我要发布/自动发布,我的应用程序崩溃了。 请帮帮我谢谢你......

4 个答案:

答案 0 :(得分:4)

return [strategy autorelease];

<强>更新
关于返回自动释放对象的答案是正确的,问题是GMGridView根据project's site中的说明使用ARC

  

要求:

     

iOS 4及更高版本Xcode 4.2(GMGridView使用ARC)
框架:基础,   UIKit,CoreGraphics和QuartzCore

所以我想你需要把它作为子模块添加到项目中,但你可以稍微搜索一下说明......

答案 1 :(得分: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,但allocnew和任何copy方法除外。

我真的建议阅读Advanced Memory Management Programming Guide

答案 2 :(得分:0)

当您返回对象时,您需要自动释放对象

return [strategy autorelease];

答案 3 :(得分:0)

return [策略自动释放]; 也  [gmGridView发布];

在函数的末尾