【问题标题】:Why are the following considered memory leaks?为什么以下被认为是内存泄漏?
【发布时间】:2012-07-19 09:47:18
【问题描述】:

我只是想知道是否有人可以向我解释为什么以下几行显示为 Instruments 内存泄漏:

self.videoEngine = [[VideoEngine alloc] initWithCallbackName:@"IntroFinished"];

self.videoEngine = [[VideoEngine alloc] initWithCallbackName:@"MainMovieFinished"];

self.timerMap = [NSTimer scheduledTimerWithTimeInterval:fps target:self selector:@selector(updateAnimationTimer) userInfo:nil repeats:YES];

NSString *locationName2 = [[NSString alloc] initWithString:[locationName substringFromIndex:test]];

初始化时不使用预设的 NSString 有问题吗?在 self.videoEngine 和 self.timerMap 的示例中,它们都具有(非原子,保留)属性,并且在使用前被合成。

【问题讨论】:

    标签: iphone xcode memory-leaks instruments


    【解决方案1】:

    如果您不使用 Arc(我认为您没有使用 Arc),那么这将是您的内存泄漏。

    当您分配 VideoEngine 属性时,它正在对您的对象执行另一个保留。您需要在 alloc 语句的末尾添加 autorelease。

    self.videoEngine = [[[VideoEngine alloc] initWithCallbackName:@"IntroFinished"] autorelease];
    
    self.videoEngine = [[[VideoEngine alloc] initWithCallbackName:@"MainMovieFinished"] autorelease];
    
    self.timerMap = [NSTimer scheduledTimerWithTimeInterval:fps target:self selector:@selector(updateAnimationTimer) userInfo:nil repeats:YES];
    
    NSString *locationName2 = [[NSString alloc] initWithString:[locationName substringFromIndex:test]];
    

    【讨论】:

    • 谢谢,你能解释一下为什么我需要自动释放它们,即使我稍后释放它们?我也想到了自己的重点。是看指针是否等于新值,如果不释放呢?我现在真的很困惑......
    • 当您像使用 VideoEngine 一样分配对象时,该对象的保留计数为 1。并且因为您的属性被声明为 (nonatomic, retain) 它也会在分配对象时增加对象的保留计数。
    • 哦,好吧,如果我执行以下操作:VideoEngine *ve = [[VideoEngine alloc] etc],然后 self.videoEngine = ve; , 然后 [ve 释放]。应该没问题吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2015-08-04
    • 2016-08-03
    相关资源
    最近更新 更多