【问题标题】:Is this usage of NSMutableString a memory leak?NSMutableString 的这种用法是内存泄漏吗?
【发布时间】:2010-10-20 00:19:57
【问题描述】:

我目前在一个类中使用一个实例变量,它是一个 NSMutableString,它是一个 NSURLConnection 的委托。该变量负责构建从委托方法返回的数据字符串:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 

字符串 'foo' 有一个属性集,并在其上设置了保留。它以这种方式非常直接地在我的类 init 方法中分配:

dataString = [[NSMutableString alloc] init];

在类的dealloc方法中释放。

在 connection:didReceiveData: 中,我使用了这样的 var:

    NSString *tmpString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [dataString appendString:tmpString];
    [tmpString release];

现在事情变得棘手了。由于我设置 NSURLConnection 委托的类是一个单例(它主要处理 NSURL* 类型调用),我需要小心如何重用我的对象。因此,在我的 connectionDidFinishLoading: 类中,我有以下内容:

   // cache away data currently in dataString.
[dataString release];
dataString = [[NSMutableString alloc] init];

这种处理我的 dataString 的策略会让你眼花缭乱吗?我在泄漏内存吗?我能做什么更聪明?

【问题讨论】:

    标签: iphone cocoa cocoa-touch objective-c memory-leaks


    【解决方案1】:

    您要问我们是否每个 use 中的object 在您的应用程序中是内存泄漏?

    Read the documentation. 学习the rules of object ownership,您每次都会得到答案。

    如果您怀疑有泄漏,请运行 Instruments 的 ObjectAlloc 探测器。 You've done this once already,很清楚你知道怎么做。还有the leaks command。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-20
      • 2013-08-12
      • 2011-01-04
      • 1970-01-01
      • 2013-01-08
      • 2013-11-12
      相关资源
      最近更新 更多