【问题标题】:Extremely weird image retaining behavior of a NSImageView [duplicate]NSImageView 的极其奇怪的图像保留行为 [重复]
【发布时间】:2012-04-03 01:32:19
【问题描述】:

我已将问题范围缩小到:

// newImage is passed from elsewhere
NSLog(@"retain count first : %lu", [newImage retainCount]);
img = newImage;
[imgView setImage:newImage];
NSLog(@"retain count next : %lu", [newImage retainCount]);
[imgView setImage:nil];
NSLog(@"retain count finally : %lu", [newImage retainCount]);

以上代码产生:

2012-03-17 21:51:04.833 App[67425:507] retain count first : 1
2012-03-17 21:51:04.833 App[67425:507] retain count next : 2
2012-03-17 21:51:04.834 App[67425:507] retain count finally : 4

如果我注释掉 [imgView setView:nil] 行,代码会生成:

2012-03-17 21:51:52.314 App[67479:507] retain count first : 1
2012-03-17 21:51:52.314 App[67479:507] retain count next : 2
2012-03-17 21:51:52.314 App[67479:507] retain count finally : 2

所以基本上[imgView setImage:nil] 将保留计数增加 2,什么时候应该减少 1?!

【问题讨论】:

  • 人们对retainCount 相关的问题很生气,因为它已经出现过很多次了。
  • 是的——否则这个问题会很好,但已经有无数个骗子了。

标签: macos cocoa memory-management nsimage nsimageview


【解决方案1】:

Don't rely on -retainCount.Really, don't.Really.

可能imgView 保留并自动发布了您的图像。保留计数现在更高,但在您的函数返回后自动释放执行其释放时会减少。 (很可能会在当前运行循环迭代结束时。)

如果您真的想知道发生了什么,请使用分配工具。打开“记录引用计数”,点击特定对象,您可以看到在该对象上调用的每个内存管理相关函数(分配、保留、释放、自动释放和释放)。比看retainCount有用多了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2013-06-28
    • 2015-07-26
    相关资源
    最近更新 更多