【问题标题】:ARC Memory release doesn't work [closed]ARC内存释放不起作用[关闭]
【发布时间】:2014-02-10 07:45:04
【问题描述】:

大家好,我阅读了许多使用 ARC 进行内存释放的示例, 他们说如果你将指针设置为 nill ARC 会为你释放它, 还有一些教程很好地解释了这件事,但在我的程序中 还是不行……

测试由以下几行组成:

while(1)
{
    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
    NSString *tmp =[formatter stringFromDate:now];
    lol = [tmp copy];
    tmp = nil;
    now = nil;
    formatter = nil;
    lol = nil;
}

它的内存大小仍在增长... 帮助我...也许我必须关闭 ARC...

【问题讨论】:

  • 你怎么知道内存在增长?
  • 我打算问同样的问题,更具体地说,是什么让你相信这个代码块是泄漏的地方?
  • 对不起,我忘记了 while 循环

标签: ios objective-c memory automatic-ref-counting


【解决方案1】:

目前尚不清楚您要使用该代码做什么,但如果您将所有内容包装在这样的 @autorelease 块中,它将对您有所帮助:

@autorelease {
    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Sydney"]];
    NSString *tmp =[formatter stringFromDate:now];
    lol = [tmp copy];
    tmp = nil;
    now = nil;
    formatter = nil;
    lol = nil;
}

【讨论】:

  • 对我来说@autoreleae 不存在...
  • 好吧,你拼错了,是@autorelease,而不是@autoreleae
【解决方案2】:

arc 可以自动释放数据,所以在一个紧密的循环中(你说你使用 while),runloop 不是高级的,autoreleasepool 也没有耗尽。

在你的循环中放置一个显式的@autoreleasepool

【讨论】:

  • 感谢它有效 ;),但是如果我有两个线程和一个类数组要在它们之间传递怎么办?我如何发布课程?
  • 如果真的没有线程访问它们,对象就会被释放
猜你喜欢
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多