これが私の2つのビューのレイアウトです。
本質的に私の目標はVC2
、MPMusicPlayerController
. unwindsegue
新しいビューのインスタンスとそのリソースが削除されたという印象を受けましたが、音楽プレーヤーは停止していません。終了する前VC2
に、すべてのメディア プレーヤーの通知を登録解除し、音楽プレーヤー自体を nil に設定する関数を実行します。ただし、戻ってきたときに音楽の再生を聞くことができ、「新しい」音楽プレーヤーコントローラーのVC1
新しいインスタンスを作成してVC2
も機能しません (通知は登録されません)。
いくつかのコード:
音楽プレーヤーがインスタンス化されています ( VC2
):
- (void)viewDidLoad
{
[super viewDidLoad];
musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
[self registerMediaPlayerNotifications];
}
登録通知:
- (void) registerMediaPlayerNotifications
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: self
selector: @selector (handle_NowPlayingItemChanged:)
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: @selector (handle_PlaybackStateChanged:)
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: @selector (handle_VolumeChanged:)
name: MPMusicPlayerControllerVolumeDidChangeNotification
object: musicPlayer];
[musicPlayer beginGeneratingPlaybackNotifications];
}
からのスニペットgetNextSong
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:test forProperty:MPMediaEntityPropertyPersistentID];
MPMediaQuery *query = [[MPMediaQuery alloc] init];
[query addFilterPredicate: predicate];
NSArray *queryResults = [query items];
for (MPMediaItem *song in queryResults) {
[musicPlayer setQueueWithQuery:query];
[musicPlayer play];
}
前に実行されるコードVC2
は「アンワインド」です:
- (IBAction)reset:(id)sender {
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerVolumeDidChangeNotification
object: musicPlayer];
[musicPlayer endGeneratingPlaybackNotifications];
[musicPlayer stops];
musicPlayer = nil;
[self performSegueWithIdentifier:@"resetRoom" sender:self];
}
に設定してもnil
、音楽は再生され続けます。これは、実際に破壊されていないことを示しています。
編集:より具体的にはVC2
、次のif
ステートメントの新しいコピーを2回目にインスタンス化すると、実行されません:
- (void) handle_PlaybackStateChanged: (id) notification
{
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if(playbackState == MPMusicPlaybackStateStopped)
[self getNextSong];
[self playbackButton];
}
インスタンス化する両方の時間でplaybackState
あることをデバッガーで確認しました。0
ただし、2 回目は、if
ステートメントは発生しません。