2012-01-16 4 views
0

일부 음악을 재생하는 uitabviewcontroller가있는 ios 앱에서 작업하고 있습니다. 각 탭 viewcontroller 자체 오디오 플레이어를 만들 싶지 않아요. 하나의 오디오 플레이어가 있고 모든 viewcontrollers가 공유하고 싶습니다.ios single AVAudioPlayer

그래서 내가 하나의이 클래스의 인스턴스와 내 모든 viewcontrollers를 만들 노래 URL로 avaudioplayer 시작하고 노래를 연주 할 선수라는 클래스,

#import <AVFoundation/AVFoundation.h> 

@interface player : NSObject { 

    AVAudioPlayer *theMainAudio; 

} 

-(void)playSong:(NSString *)songName; 

@end 

공유를 만들었습니다. 내가하는 .m 파일에

@interface AppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { 

    UIWindow *window; 
    UITabBarController *tabBarController; 
    player *theMainPlayer; 

} 

@property (nonatomic, retain) IBOutlet UIWindow *window; 
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController; 
@property (nonatomic, retain) player *theMainPlayer; 

@end 

,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

    //some other stuff here.... 

    theMainPlayer = [[player alloc]init]; 

    return YES; 
} 

을 한 후 내 viewcontrollers에라고

player myPlayer = ((AppDelegate *)[UIApplication sharedApplication].delegate).theMainPlayer; 

, 내 대리자를 만드는 시도했지만이하지 않았다 작업. 누구나 내가 한 일이나 내가하고 싶은 일을하는 다른 방법이 있다면 무엇이 잘못되었는지 나에게 말할 수 있습니다. 이는 플레이어 개체를 만들고 모든 내 viewcontrollers에서 공유하는 것입니다.

감사합니다.

답변

3

, 그냥 player.h을 가져

[[player sharedInstance] playSong:@"something"]; 
+0

당신은 완전히 내 목숨을 구했습니다! 너는 내가 얼마나 많은 시간을 할애했는지 모른다. 고맙습니다! – Mona

0

어떻게 잘못 되었나요? 내게 마지막 줄 컴파일 오류가 발생할 것이라고 보인다. 클래스 선언을 위해 별표를 추가해야합니다 :

player * myPlayer = ((AppDelegate *)[UIApplication sharedApplication].delegate).theMainPlayer; 

그 외, 나는 아무것도 잡지 않았습니다. 하지만이 경우 Singleton 패턴을 사용하는 것을 선호합니다.

참고 :이 클래스를 사용하도록 player.m

#import "player.h" 

@implementation player 

static player *sharedInstance = nil; 

+ (player *)sharedInstance { 
    if (sharedInstance == nil) { 
     sharedInstance = [[super allocWithZone:NULL] init]; 
    } 

    return sharedInstance; 
} 

- (id)init 
{ 
    self = [super init]; 

    if (self) { 
     // Work your initialising here as you normally would 
    } 

    return self; 
} 

-(void)playSong:(NSString *)songName 
{ 
    // do your stuff here 
} 

에 싱글을 만들

http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html

http://www.galloway.me.uk/tutorials/singleton-classes/