iPhone 错误,“引用计数的对象在释放后使用错误” ;内存泄漏清理
我正在尝试解决现有 iPhone 应用程序中的内存泄漏和其他问题。我对 Objective C 有点陌生,但有一些良好的编程基础,并且对开发 iPhone 应用程序时所需的内存管理有大致的了解。我的问题是关于下面的方法。
-(NSDate *)formatDate:(id)value{
NSLog(@"eja: DetailViewController/ formatDate()");
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
[dateFormatter release];
return [dateFormatter dateFromString:value];
}
它返回一个错误,读取“引用计数的对象在释放后使用”。我看到 dateFormatter 在返回/使用之前已被释放。当然,问题是,如果将释放放在 return 语句之后,则会出现与 dateFormatter var 声明相关的“对象潜在泄漏”错误。
我也尝试过“autorelease”,
return [[dateFormatter dateFromString:value] autorelease];
但随后收到错误“发送对象 - 自动释放次数过多”。
关于如何正确编写此内容以便正确管理变量有什么建议吗?
I am trying to clean up memory leaks and other issues in an existing iPhone app. I am a little new to Objective C, but have some good programming fundamentals and a general understanding of the memory management that is required when dev'ing iphone apps. My question is about the following method below.
-(NSDate *)formatDate:(id)value{
NSLog(@"eja: DetailViewController/ formatDate()");
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
[dateFormatter release];
return [dateFormatter dateFromString:value];
}
It is returning an error reading "Referenced-counted object is use after it is released". I see that dateFormatter is being freed before it is returned/used. The issue is of course that if you put the release after the return statement you get a 'Potential leak of an object' error associated with dateFormatter var declaration.
I also tried "autorelease"
return [[dateFormatter dateFromString:value] autorelease];
But I then get the error 'Object sent - autorelease too many times'.
Any words of advice on how to write this properly so the variables are properly managed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
替换
为
,它应该可以工作!
Replace
with
and it should work!
您可以在释放
NSDateFormatter
之前创建一个NSDate
:这样,您分配的
NSDateFormatter
就会按预期被释放,而您返回的对象则不会不需要手动内存管理。You can create an
NSDate
before you release theNSDateFormatter
:This way, your allocated
NSDateFormatter
gets released as it should while the object you are returning doesn't require manual memory management.您可以自动释放它,而不是编写
[dateFormatter release]
,甚至可以在此过程中节省一行代码。Instead of writing
[dateFormatter release]
, you can autorelease it, and even save a line of code in the process.