2012-01-16 14 views
0

私はいくつかの音楽を演奏するuitabviewcontrollerのiosアプリで作業しています。私は各タブのviewcontrollerがそれ自身のオーディオプレーヤーを作成する必要はありません。私は単一のオーディオプレーヤーを持ち、すべてのビューコントローラーがそれを共有したいと思っています。ios single AVAudioPlayer

ので、私は、このクラスのインスタンスを1つだけ作成したいとすべての私のviewcontrollersがそれを共有し、

#import <AVFoundation/AVFoundation.h> 

@interface player : NSObject { 

    AVAudioPlayer *theMainAudio; 

} 

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

@end 

を曲のURLでavaudioplayerを開始し、歌を果たしているでしょうプレーヤーと呼ばれるクラスを作成しました。私は.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; 

、私のデリゲートでそれを作成しようとしましたが、これはしませんでした作業。 私は何をやったのか、あるいはプレイヤーオブジェクトを作成してすべてのビューコントローラーで共有するために、他にやりたいことをする方法があれば誰にでも教えてもらえますか?

ありがとうございました

答えて

3

は、ちょうどplayer.hをインポート

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

あなたは完全に私の人生を救った!あなたは私がこれに費やした時間は分かりません。ありがとうございました! – Mona

0

どうしたのですか?私にとっては、最後の行がコンパイルエラーの原因になるようです。あなたは、クラス宣言にアスタリスクを追加する必要があります。それ以外は

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

は、私が何かをキャッチしていません。 しかし、このような場合にはシングルトンパターンを使用することをお勧めします。

参考:このクラスを使用するように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/