Sending a message to an object
I'm pretty new to Objective C but things are progressing well. However, I think I'm missing a key concept relating to how objects are created and messaged. I hope someone can help me.
I'm creating an iPhone app that simply creates a MPMusicPlayer, and starts playing a song from the que.
I create the music player (myPlayer) in the AppDelegate like so...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the main view controller's view to the window and display.
[window addSubview:mainViewController.view];
[window makeKeyA开发者_C百科ndVisible];
// instantiate a music player
MPMusicPlayerController *myPlayer =
[MPMusicPlayerController applicationMusicPlayer];
// assign a playback queue containing all media items on the device
[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
// start playing from the beginning of the queue
[myPlayer play];
return YES;
}
This works fine. Now in the MainViewController I try to send myPlayer the command to skip to the next track
[myPlayer skipToNextItem];
However when I try to compile I get the message that myPlayer in undeclared.
What am I doing wrong? I can see how I could fix this in a procedural way (by creating the player in the MainViewController), but I'd like to understand what I have to do to get it working in and OOP way.
Cheers,
Richard
Most propably, the mPlayer object is unknown to your ViewController. There are two options for you:
- Make the mPlayer a property of your app delegate
- Make the mPlayer a property of your view controller subclass and set it to your mPlayer upon creation
In your appdelegates declaration, do:
@property(nonatomic, retain) MPMusicPlayerController *mPlayer;
In your appdelegates implementation, do:
@synthesize mPlayer;
In your viewcontroller, do:
MPMusicPlayerController *mPlayer = [[[UIApplication sharedApplication] delegate] mPlayer];
精彩评论