以下哪种情况是正确的编码习惯,因为播放器是(非原子的,保留的),并且是使用player = _player合成的。
情景A
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.player = mp;
[mp release];
情景B
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
self.player = mp;
到目前为止,我一直在使用方案A作为一般做法,但我认为这可能导致我的代码中的内存泄漏。
感谢您的帮助。
编辑1:
同样适用于计时器,它们给我带来了麻烦。如果我使用下面的代码是正确的吗?如果timerMap也是(非原子,保留),并使用timerMap = _timerMap;
self.timerMap = [[NSTimer scheduledTimerWithTimeInterval:fps target:self selector:@selector(updateAnimationTimer) userInfo:nil repeats:YES] autorelease];
当释放时,只是无效,或者它应该是无效然后释放吗?
答案 0 :(得分:4)
场景A绝对是要走的路,场景B会泄漏mp
来源:Apple Doc
编辑1:
您发布的代码错误,再次设置timerMap
属性时会导致崩溃。你不能autorelease
它
self.timerMap = [NSTimer scheduledTimerWithTimeInterval:fps target:self selector:@selector(updateAnimationTimer) userInfo:nil repeats:YES];
当你不再需要计时器时,只需
self.timerMap = nil;
这将调用计时器上的release
方法,并将指针设置为nil
答案 1 :(得分:1)
情景A是正确的。场景B实际上会导致内存泄漏,这是因为self.player = mp;保留参考柜台。
以下代码也是正确的:
MPMoviePlayerController *mp = [[[MPMoviePlayerController alloc] initWithContentURL:movieURL] autorelease];
self.player = mp;
答案 2 :(得分:1)
第一个是正确的内存管理,但我倾向于选择:
self.player = [[[MPMoviePlayerController alloc]
initWithContentURL:movieURL]
autorelease];
这样我就可以将该对象的所有内存管理保留在一行
EDIT 以下编辑问题
您拥有的计时器对象已自动释放,您不应再次向其添加autorelease
。有关方便方法的解释,请查看this question。