Objective C NSMutableString* 属性保留计数怪异
如果我创建一个 nsmutablestring 然后释放它,保留计数不应该为 0 吗?
我的保留计数保持为 1。
NSMutableString *text = [[NSMutableString alloc]init];
[text release];
NSLog(@"retain count %d ", [text retainCount]);
我错过了什么吗?
谢谢。
if I create an nsmutablestring and then release it , shouldn't the retain count be 0?
my retain count stays 1.
NSMutableString *text = [[NSMutableString alloc]init];
[text release];
NSLog(@"retain count %d ", [text retainCount]);
Am I missing something ?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无法保证
retainCount
在对象生命周期的任何时刻都会返回正确的值。如果您使用[[NSMutableString alloc] init]
创建了一个NSMutableString
并且您对它调用了一次release,那么您正在做正确的事情,而不应该这样做担心它。There's no guarantee that
retainCount
will return the correct value at any point during the object's lifecycle. If you've created anNSMutableString
using[[NSMutableString alloc] init]
and you're calling release on it once, you're doing the right thing and shouldn't worry about it.苹果在其文档中表示,retainCount 对于内存管理目的没有用处,因为即使您已经释放了对象,框架和自动释放池也可以保留该对象。 http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retainCount< /a>
Apple says in its documentation that retainCount is of no use for memory management purposes because the frameworks and autorelease pools can keep hold of an object even if you have released it. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retainCount
由于您这样做是出于调试目的,因此我建议您使用类别向现有类添加一些测试代码。每当您手动保留或释放对象时,您都可以调用新方法并使用它来跟踪内存使用情况。
Since you're doing this for debugging purposes, I'd suggest that you use categories to add some test code to an existing class. Any time you manually retain or release your object, you could call your new methods and use that to track your memory usage.