美好的一天。
我正在开发一款可以播放多种音乐的应用程序,但是当我在侧边栏选择分享时,我会停留在音乐停止的位置(我希望音乐继续播放,因为用户没有暂停) 我正在使用来自RESideMenu的api,我怀疑initRootController是导致音乐停止的原因。
有人建议我将音乐放在appDelegate上,因为当切换视图控制器时音乐可能会被取消分配。但是,我认为这不是一个好方法,因为我稍后将添加更多具有不同图像背景的音乐,并且应用程序的架构将非常混乱,因为我在ThemeObject中存储每个音乐并在cafeViewController中调用音乐。
有更好的方法吗?
这是我的代码>>>源。
答案 0 :(得分:0)
我检查了您的回购,声音似乎发生在您的ThemeObject中,而您创建和链接其中一个的唯一地方就在您的CafeViewController中。所以每次CafeViewController被卸载时,这将删除对ThemeObject的唯一引用,并且它将被垃圾收集。要检查CafeViewController是否被卸载,您可以在此方法中放置一个断点:
- (void)dealloc {
// Just a line where you can put your breakpoint
}
将它放在AppDelegate中的建议并不完全倒退,因为你最好将它放在一个始终存在的对象中。然而,滥用AppDelegate作为所有集中功能的倾销场是一种不好的做法。对于简单的应用程序,使用Singleton方法可能会更好,在这种方法中,您始终拥有一个对象实例,并且该对象在应用程序存在期间保持自身。
这是典型的单身人士的样子:
@interface ThemeManager : NSObject
@property NSArray *themes;
+ (id)sharedManager;
// Add other methods here
@end
@implementation ThemeManager
+ (id)sharedInstance {
static ThemeManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
ThemeObject *cafeTheme = [[ThemeObject alloc] initWithBackgroundImg:@"cafeBG.png" audio:@"cafeAudio"];
ThemeObject *cafeTheme1 = [[ThemeObject alloc] initWithBackgroundImg:@"cafeBG.png" audio:@"cafeAudio"];
// Create as much as you need in the same way
self.themes = @[cafeTheme, cafeTheme1]; // And add them to the array of themes
}
return self;
}
// Implement other methods
@end
所以你永远不会直接初始化,但总是通过调用类似
的东西来请求共享实例MusicManager *manager = [MusicManager sharedInstance];
ThemeObject *firstTheme = (ThemeObject *) [manager.themes firstObject];
[firstTheme setAudioPlay];
您可以使用此中心对象启动,暂停,停止和更改歌曲,而无需担心ViewControllers的生命周期。您也可以从例如CafeViewController开始播放歌曲,当您启动酒店歌曲时,您可以停止从HotelViewController启动的歌曲CafeViewController。