我做了一个名为MyBgMusic.h的单例类& MyBgMusic.m。如何将单例类引用到我的SecondViewController或XIB的其余部分。
这是我的单身人士课程:
H档:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface MyBgMusic : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
UIButton *playBgMusic;
}
@property (nonatomic, retain) IBOutlet AVAudioPlayer *player;
@property (nonatomic, retain) IBOutlet UIButton *playBgMusic;
+ (id)sharedManager;
-(IBAction) toggleMusic;
@end
M档案:
#import "MyBgMusic.h"
static MyBgMusic *sharedMyManager = nil;
@implementation MyBgMusic
@synthesize player,playBgMusic;
#pragma mark -
#pragma mark Singleton Methods
+ (MyBgMusic*)sharedManager {
static MyBgMusic *sharedMyManager;
if(!sharedMyManager) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedMyManager = [[super allocWithZone:nil] init];
});
}
return sharedMyManager;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedManager];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
#if (!__has_feature(objc_arc))
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (id)autorelease {
return self;
}
- (void)dealloc
{
[MyBgMusic release];
[playBgMusic release];
[player release];
[super dealloc];
}
#endif
#pragma mark -
#pragma mark Custom Methods
- (IBAction)toggleMusic {
if ([self.player isPlaying] == YES) {
[self.player stop];
} else {
[self.player play];
}
self.playBgMusic.enabled = YES;
}
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
player.delegate = self;
[player play];
player.numberOfLoops = -1;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
SecondViewController.m(我想从单例类中引用,以便我可以重新使用它,而不会在按下和关闭时弄乱背景音乐。)
- (IBAction)toggleMusic{
if ([self.player isPlaying] == YES) {
[self.player stop];
} else {
[self.player play];
}
self.playBgMusic.enabled = YES;
}
我应该这样声明:
-(IBAction) sharedMusic {
[[MyBgMusic sharedManager] toggleMusic]; // instance method shareManager not found. What does it mean?
}
答案 0 :(得分:0)
在SecondViewController中创建一个IBAction,然后在代码中挂起xib,然后调用
[[MyBgMusic sharedInstance] toggleMusic];
答案 1 :(得分:0)
在SecondViewController中,当你想要切换音乐时,你应该在IBAction中调用[[MyBgMusic sharedInstance] toggleMusic];
。就像你使用self.player
一样。
答案 2 :(得分:0)
您必须导入您的班级并使用此行在任何地方引用它:
[[MyBgMusic sharedManager] toggleMusic]
如果需要,您可以添加偶数属性并引用它,而无需创建类的实例。