问题描述
我已经完成了一个名为MyBgMusic.h& MyBgMusic.m.如何将该单例类引用到我的SecondViewController或XIB的其余部分.
I have done a singleton class called MyBgMusic.h & MyBgMusic.m. How to reference that singleton class to my SecondViewController or the rest of the 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(我想从单例类中进行引用,以便可以再次使用它,而不必在打开和关闭时弄乱背景音乐.)
SecondViewController.m ( I want to reference from the singleton class so that I can use it all over again without mess up the background music when pressing on and off. )
- (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?
}
推荐答案
您必须导入您的类,并在希望使用此行的任何位置引用它:
You have to import your class and reference it wherever you want using this line :
[[MyBgMusic sharedManager] toggleMusic]
如果需要,您可以添加偶数属性并引用它,而无需创建类的实例.
If you want, you can add even property and reference it without create an instance of your class.
这篇关于iOS:如何从单例类中引用音乐背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!