4th*_*ace 26 iphone memory-management mpmovieplayercontroller
我有几个访问电影播放器的观点.我已将以下代码放在AppDelegate中用于这些视图的方法中.他们发送文件名进行播放.代码工作正常,但我知道某个地方需要发布.如果我将最后一行添加为发布或自动释放,则一旦用户在电影播放器上按下完成,应用程序将崩溃.
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:[NSURL fileURLWithPath:moviePath]];
moviePlayer.movieControlMode = MPMovieControlModeDefault;
[moviePlayer play];
//[moviePlayer release];
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
objc [51051]:FREED(id):消息videoViewController发送到释放对象= 0x1069b30
程序收到信号:"EXC_BAD_INSTRUCTION".
我该如何发布播放器?
小智 18
我发现MPMoviePlayerController必须先发送停止消息才能安全地释放它.所以我在handlePlaybackEnd中执行 - 首先我停止它,然后我自动释放它.调用版本似乎不太好用:
- (void) moviePlayBackDidFinish : (NSNotification *) notification
{
VideoPlayerController * player = notification.object;
[player stop];
[player autorelease];
}
Run Code Online (Sandbox Code Playgroud)
整个事情变得有点棘手,因为MPMoviePlayerPlaybackDidFinishNotification可以多次发送,但是调用stop/autorlease两次也不会对你有任何帮助.所以你需要以某种方式防范这种情况.
最后,似乎需要对主运行循环进行一些迭代,直到您可以安全地创建新的MPMoviePlayerController实例.如果你做得太快,你会得到声音,但没有视频.真好玩,对吧?
要回答4thSpace对上述答案的评论,您可以删除通知观察者,以免多次收到:
- (void)moviePlayBackDidFinish:(NSNotification *)notification {
MPMoviePlayerController *theMovie = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
[theMovie stop];
[theMovie release];
}
Run Code Online (Sandbox Code Playgroud)