日安。
我正在开发一个用于播放多种音乐的应用程序,但当我在侧边栏选择“共享”(我希望音乐继续播放,因为用户没有暂停它)时,我被困在音乐停止的地方了。我正在使用来自RESideMenu的api,我怀疑initRootController是导致音乐停止的原因。
有人建议我将音乐放在appDelegate上,因为音乐在切换视图控制器时可能会被取消分配。然而,我认为这不是一个好的方法,因为我将添加更多的音乐,具有不同的图像背景和架构的应用程序将非常混乱,因为我储存每一音乐在ThemeObject和调用音乐在cafeViewController。
有更好的方法吗?
这是我的代码>>>源代码。
发布于 2014-12-19 03:28:33
我已经检查了您的回购,声音似乎发生在您的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。
https://stackoverflow.com/questions/27559008
复制相似问题