我在我建立的名为MPMoviePlayerController
的类中使用MYVideo
。这是代码:
#import <MediaPlayer/MediaPlayer.h>
#import "MYVideo.h"
@interface MYVideo()
@property (strong, nonatomic) UIView * viewRef;
@property (strong, nonatomic) NSDictionary * contentData;
@property (strong, nonatomic) MPMoviePlayerController * videoController;
@end
@implementation MYVideo
@synthesize contentData,videoController,viewRef;
- (MYVideo*) initIntoView: (UIView*) view withContent:(NSDictionary*)contentDict{
self=[super init];
viewRef=view;
contentData = contentDict;
NSString *rawUrl = [[NSString alloc] initWithFormat:@"http://....com/app/%@.mp4", [contentDict objectForKey:@"cnid"]];
NSURL *videoUrl = [[NSURL alloc]initWithString:rawUrl];
videoController = [[MPMoviePlayerController alloc] initWithContentURL:videoUrl];
videoController.movieSourceType=MPMovieSourceTypeFile;
videoController.view.frame = viewRef.bounds;
[videoController.view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
videoController.controlStyle=MPMovieControlStyleNone;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackFinished:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:videoController];
[viewRef addSubview:videoController.view];
return self;
}
- (void) playbackFinished: (NSNotification*) notification {
NSLog(@"playback finished");
if(videoController){
[videoController play];
}
}
- (void) play: (int) offset {
videoController.initialPlaybackTime=offset;
[videoController play];
}
- (void) stop {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"playbackFinished"
object:nil];
if(videoController){
[videoController stop];
}
}
- (void) destroy {
if(videoController){
[videoController stop];
[videoController.view removeFromSuperview];
}
}
@end
我的问题是我偶尔会收到以下错误:
playback finished
-[__NSCFString playbackFinished:]: unrecognized selector sent to instance 0x1664e6a0
我猜这是由MPMoviePlayerController
在此视频类发布时触发“playbackFinished”通知引起的。我是否正确地想到了这一点?
事实是,这个MYVideo
类应该在播放视频时仍然存在,此错误仅在视频播放时发生,并且在控制台日志中,我的NSLogging“播放完成”立即在崩溃之前。在没有先删除“playbackFinished”观察者的情况下,我也从未关闭过课程。
有人可以告诉我为什么我会遇到这次崩溃吗?
非常感谢。
答案 0 :(得分:3)
是的,看起来你没有删除观察者,就像这段代码:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"playbackFinished"
object:nil];
应该是:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"playbackFinished:"
object:nil]; // ^
或更好(因为你并不关心所谓的):
[[NSNotificationCenter defaultCenter] removeObserver:self
name:nil
object:videoController];
另外,如果您在很多地方使用if (videoController) { ... }
等测试,则需要尽快确保nil
:
- (void)destroy {
if(videoController){
[videoController stop];
[videoController.view removeFromSuperview];
videoController = nil; // Add
}
}