views:

46

answers:

1

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 makeKeyAndVisible];

// 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

+1  A: 

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];
Toastor
Toastor, this is all great advice regarding ivars and properties, and the OP certainly needs to know all this... however, I think it is slightly misleading in this particular case because the OP is wanting to access a singleton object, which (s)he can easily do just using [MPMusicPlayerController applicationMusicPlayer] again from the view controller object. This is probably more formally correct also (although obviously keeping a reference to a singleton is generally safe in practice).
Echelon
Cheers, that did the job.
Shadrax