【问题标题】:memory management on Protocol协议上的内存管理
【发布时间】:2012-05-22 06:53:11
【问题描述】:

我正在使用协议,并且正在泄漏, 这是我的代码:

+ (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;
}

如果我做自动释放,那么它会崩溃。那么我现在该怎么办?请帮助我... 谢谢...

【问题讨论】:

  • 当它与 autorelase 一起崩溃时?在这个方法还是在外面?

标签: ios cocoa-touch memory-management


【解决方案1】:

在您的strategyFromType 函数中

return [strategy autorelease];

当你调用这个函数时使用retain

GMGridViewLayoutStrategy *strat = [[YourClassName strategyFromType:yourType] retain];

使用strat变量后

[strat release];

【讨论】:

  • 我可以在那里写自动释放吗?
  • '那里'是什么意思?您可以像我所做的那样使用 return 语句编写 autorelease.. 或者您可以使用 [[[yourClass alloc ] init] autorelease]
  • 嗨,我有自定义标签栏。在标签栏中,当我返回时,我正在使用 NSNotificationCenter 调用一种方法。在该方法中,我只是释放所有对象。但是当我在仪器中检查它时,我发现分配的对象不会dealloc。代码在这里:-(void)backBtnPessed { [[NSNotificationCenter defaultCenter] postNotificationName:@"GeneralViewController" object:nil]; [self.navigationController popViewControllerAnimated:YES]; }请帮助我。谢谢...
【解决方案2】:
-(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 autorelease];
}

在调用方..

GMGridViewLayoutStrategy *obj = [[YourClassName strategyFromType:yourType] retain];

使用“obj”后释放它。

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2015-11-19
    相关资源
    最近更新 更多