-1

Possible Duplicate:
Passing Data between View Controllers

I'm having a strange problem with Xcode I just cant understand.

@interface MenuViewController : UIViewController{
    AVAudioPlayer *audioPlayer;
}

That is something I have implemented in one view and in another i tried using that audio player and it didn't work. Yes, I have imported this view controller in my other view. Can anyone help.

Community
  • 1
  • 1
user1612646
  • 69
  • 2
  • 11

2 Answers2

0

You should use a property instead of an instance variable to be able to access the AVAudioPlayer from other classes:

@interface MenuViewController : UIViewController {
}

@property (retain) AVAudioPlayer* audioPlayer;

In the other View Controller you can then get audioPlayer using

[myMenuViewController audioPlayer]
s1m0n
  • 7,825
  • 1
  • 32
  • 45
  • where would I put that second piece of code – user1612646 Nov 28 '12 at 16:08
  • I don't know how you get a reference to `MenuViewController` in your other view.. You can replace `myMenuViewController` by the name of the variable `MenuViewController` is stored in – s1m0n Nov 28 '12 at 16:53
0

This is a feature of OOP. Depending on what you want to do you need to do one of two things. Either instantiate the object in both places or instantiate it in one place and pass it to the other. If you want to pass it, you could use something like NSNotification. In the class that is going to use the shared audioPlayer you could do something like:

- (id)init
{
  self = [super init];
  if (self) {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(incomingAudioPlayer:)
                                                 name:@"ShareAudioPlayer" 
                                               object:nil];
  }
  return self;
}

- (void)incomingAudioPlayer:(NSNotification *)notification {
  // do stuff here
}

And in the class where you instantiate audioPlayer (just after the instantiation) you could do:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ShareAudioPlayer" 
                                                            object:self
                                                          userInfo:audioPlayer];

Actually you might have to play with userInfo and stick audioPlayer in an NSDictionary or something, but this should get you closer. This is the method I normally use, there may be others.

Ricky Nelson
  • 876
  • 10
  • 24