【问题标题】:Can't release the variable in objective-c ios [duplicate]无法在objective-c ios中释放变量[重复]
【发布时间】:2013-04-07 17:40:33
【问题描述】:

我有这个功能,我不使用ARC:

-(NSString *)getDataFileDestinationPath      
{
    NSMutableString *destPath = [[NSMutableString alloc] init];
    [destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
    [destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
    return destPath;
    [destPath release];
}

因此,如果没有发布消息,我在泄漏分析中会有很大的内存泄漏。所以我添加了[destPath release]; 消息,但是当我尝试使用这个方法时——正如我在调试过程中看到的那样——这行代码根本没有被调用。因此,在返回消息后,控件转到下一个方法。我应该在哪里实现释放功能来释放内存?

【问题讨论】:

  • 首先,不要在方法前面加上get;这是为特殊情况保留的(不是​​这样)。其次,return 语句之后的任何内容都不会被执行。
  • @bbum 谢谢,我忘了 get 前缀!

标签: ios objective-c memory-management


【解决方案1】:

这就是 autorelease 的发明目的。

return [destPath autorelease];

或者最初不分配初始化字符串对象,只需创建一个最初自动释放的实例:

NSMutableString *destPath = [NSMutableString string];

【讨论】:

    【解决方案2】:

    在这种情况下你需要使用自动释放。

        -(NSString *)getDataFileDestinationPath      
    {
        NSMutableString *destPath = [[NSMutableString alloc] init];
        [destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
        [destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
        [destPath autorelease];
        return destPath;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多