【问题标题】:Why isnt this objective-c IOS code leaking?为什么这个objective-c IOS代码没有泄露?
【发布时间】:2012-01-30 08:35:48
【问题描述】:

我正在重用 surl,所以它似乎会泄漏。但是仪器没有显示链接。我一定不明白它如何在不创建垃圾字符串的情况下重用它。

NSString *rcode = @"DDD";

NSString *surl = [NSString stringWithFormat: @"http://www.myweather.com/%@_%@.png", rcode, @"7"];
NSURL *url = [NSURL URLWithString: surl]; 
UIImage *image7 = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

surl = [NSString stringWithFormat: @"http://www.myweather.com/%@_%@.png", rrcode, @"6"];
url = [NSURL URLWithString: surl]; 
UIImage *image6 = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

surl = [NSString stringWithFormat: @"http://www.myweather.com/%@_%@.png", rrcode, @"5"];
url = [NSURL URLWithString: surl]; 
UIImage *image5 = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

【问题讨论】:

  • ObjC 现在没有像样的 GC 了吗?
  • @cHao Objective C for Mac OS X 开发可以使用 GC。对于 iOS,没有 GC。但是对于 iOS 5 sdk,他们添加了 ARC

标签: xcode ios5 nsstring instruments memory-leaks


【解决方案1】:

看看这一行:

[NSString stringWithFormat: @"http://www.myweather.com/%@_%@.png", rcode, @"7"];

+[NSString stringWithFormat:] 是一个“便利构造函数”,有时也称为“便利方法”,它返回一个您不拥有的 NSString,因此除非您选择自己保留它,否则您没有任何责任释放它(你没有)。

基本规则是,如果您从以“alloc”、“new”、“copy”或“mutableCopy”开头的方法中获取对象,则您有责任释放它。否则,你不会。

无论有没有 ARC,我都没有看到泄漏。

【讨论】:

    【解决方案2】:

    此代码没有泄漏,因为它使用了“自动释放”对象。

    您编写的所有对象创建代码都使用返回自动释放对象的便捷方法。这意味着这些将在相应的自动释放池被释放时被释放。

    请参阅 Apple 的 Advanced Memory Management Programming Guide 中的此页面以了解有关自动释放的更多信息。

    【讨论】:

    • 感谢您的链接!和反馈!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多