开发者

How do i reference something in another class?

开发者 https://www.devze.com 2023-02-07 15:26 出处:网络
In fliteTTS.h, it has: AVAudioPlayer* audioPlayer; And in fliteTTS.m it has: [audioPlayer stop]; audioPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:tempFilePath] erro

In fliteTTS.h, it has:

AVAudioPlayer* audioPlayer;

And in fliteTTS.m it has:

[audioPlayer stop];
audioPlayer =  [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:tempFilePath] error:&err];
[audioPlayer setDelegate:self];
[audioPlayer play];

But i want to put that last line, audioPlayer play, into my viewC开发者_StackOverflow社区ontroller class instead. How would i re-write this line to work there?


Dont return the object. Instead tell the fliteTTS object to play.

Add a method to fliteTTS:

-(void)play {
  [audioPlayer play];
}

Now instantiate your fliteTTS in your view controller, and then call

[myFliteTTSInstance play]

Doing it this way allows the class that owns the audio player to do other setup and teardown you may want to do when it starts playing. The idea is to sort of wrap the audio player with the object that owns it, instead of directly accessing it from who knows where.


Alternatively, you could create a method to return the audio player directly.

-(AVAudioPlayer*)audioPlayer {
  return audioPlayer;
}

And then from your view controller, you would call

[[myFliteTTSInstance audioPlayer] play];

But this is more brittle for a variety of reasons. If you fliteTTS class holds the instance of the audio player, it should also be able to control it for you. So do it the first way if you can.


Assuming the class is called fliteTTS, you could define a "play" method in fliteTTS.h.

- (void)play;

And then implement it in fliteTTS.m.

- (void)play {
    [audioPlayer play];
}

Then in your view controller you can call...

fliteTTS *myFliteTTS = [[fliteTTS alloc] init];
[myFliteTTS play];
[myFliteTTS release];
0

精彩评论

暂无评论...
验证码 换一张
取 消