【问题标题】:Can not call method from another view controller in Objective C, iPhone SDK无法从Objective C,iPhone SDK中的另一个视图控制器调用方法
【发布时间】:2011-02-15 21:57:25
【问题描述】:

在我的 StartWorkoutViewController.m 我触发:

    #import "WorkoutViewController.h"
@implementation StartWorkoutViewController

- (IBAction) start
{   
[firstViewController performSelector:@selector(callMyAction)];
WorkoutViewController *ViewCon = [[WorkoutViewController alloc]init];
[ViewCon callMyAction];
[ViewCon release];
}

然后在我的 WorkOutViewController.h 我添加了这个:

- (void)callMyAction;

在我的 WorkOutViewController.m 我添加了这个:

#import "StartWorkoutViewController.h"

-(void)viewWillAppear:(BOOL)animated{
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/achtergrondgeluid.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;
    [audioPlayer play];


}
-(void)callMyAction{
    NSLog(@"suckers");

    [audioPlayer pause];
}

现在我的 NSLog (@"suckers") 可以很好地从 StarWorkoutViewController 触发,但由于某种原因,audioPlayer 什么也没做,知道吗?还通过此文件中的 callMyAction 在 Workout ViewController 中设置标签。不要工作!任何的想法?谢谢!

【问题讨论】:

  • 你的-(void)callMyAction() 应该是play 还是pause 音频播放器?
  • 暂停!就像它在那里一样!也没有编译错误!
  • 好的,如果你pause播放器,你希望播放器做什么?如果您不调用callMyAction,播放器会播放url 的内容吗?
  • viewwillappear 或viewdidload 函数触发audioplayer 播放,另一个viewcontroller。在我的例子中,StarWorkoutViewController 会触发 WorkoutViewController 中的 callMyAction 来暂停播放器。
  • audioPlayernil 不同吗?如果是nil,检查error的内容。

标签: iphone objective-c class methods


【解决方案1】:

没有发生任何事情的原因是因为您在播放器开始播放之前调用了 pause 方法。 viewWillAppear 直到它在屏幕上可见时才会被调用。它实际上并不总是被调用,但这完全是另一个问题。因此,如果您想暂停播放器,它需要实际播放。如果您将该 viewWillAppear 代码放在 viewDidLoad 中,它可能会按预期工作。

目前您的代码正在执行此操作:

  1. 加载 WorkoutViewController
  2. 暂停音频
  3. WorkourViewController 变得可见(实际上这可能永远不会发生,因为我没有看到它被添加到任何窗口或任何东西)。
  4. 播放音频。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2011-12-11
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多