【问题标题】:Objective-C delegate function not working correctlyObjective-C 委托功能无法正常工作
【发布时间】:2012-09-16 18:40:41
【问题描述】:

我有一个具有三个视图的应用程序。所有三个视图在屏幕底部都有一个广告横幅。第一个视图创建一个音频流媒体,当单击此视图上的广告横幅时,该音频流媒体会暂停。我正在尝试在第二个视图上使用 AdBanner 委托方法来停止/启动音频。选择广告横幅后,AdBanner 委托方法应调用我的自定义委托函数。代码可以编译运行,但不能正常运行。

使用 NSLog,我确定广告横幅正确调用了它的委托函数,但这不是调用自定义委托。

希望这是有道理的。任何帮助,将不胜感激。这是我的代码。

SecondViewControler H 文件

#import "SecondViewController.h"

@protocol demoViewControllerDelegate <NSObject>
@required

-(void)stopSent;
-(void)startSent;

@end

@interface SecondViewController ()
{    
    id<demoViewControllerDelegate> delegate;
}    
@property (nonatomic, assign) id<demoViewControllerDelegate> delegate;
@end

SecondViewController M 文件

@implementation SecondViewController
@synthesize delegate;

协议

- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave {
    [delegate stopSent];
    return YES;
}

- (void)bannerViewActionDidFinish:(ADBannerView *)banner{
[delegate startSent];
}

FirstViewController H 文件

#import <QuartzCore/QuartzCore.h>
#import "iAd/iAd.h"
#import <MessageUI/MessageUI.h>
#import "AudioStreamer.h"
#import "Reachability.h"
#import "SecondViewController.h"
#import "MFAppDelegate.h"
#import "MFSideMenu.h"

Class secondViewConroller;

@interface DemoViewController : UIViewController <ADBannerViewDelegate,demoViewControllerDelegate> {
}

@end

FirstViewController M 文件

-(void)stopSent{
    if (isPlaying) {
        [streamer stop];
        wasPlaying=true;
    }
}

-(void)startSent{
    if (wasPlaying) {
        [streamer start];
         isPlaying=true;
    }
 }

【问题讨论】:

  • 这些委托方法实际定义在哪里? “demoViewControllerDelegate”还是“ADBannerViewDelegate”?你的 .h 文件没有说。
  • AdBannerViewDelegate 函数只是标准的 Xcode 实现。
  • 我已经修改了原帖,添加了我遗漏的代码。
  • 与 Xcode 无关。重新标记。
  • 你检查了bannerViewActionShouldBeginbannerViewActionDidFinish方法中的delegate是否不为零?

标签: objective-c delegates protocols


【解决方案1】:

您的协议方法需要在您指定为委托目标的类中实现。

看起来您的 DemoViewController(或 FirstViewController)是您指定为委托的对象,因为您已指定接口“&lt;ADBannerViewDelegate,demoViewControllerDelegate&gt;”。

然后,从您的第二个视图控制器中,您可以调用您指定的对象并将其设置为委托:

[delegate startSent];

[delegate stopSent];

在适当的位置,分别显示为“bannerViewActionShouldBegin”和“bannerViewActionDidFinish”。

您还应该确保代理设置正确,因此不要:

[delegate startSent];

你应该实际上这样做:

if(delegate)
    [delegate startSent];
else
    NSLog( @"delegate is null; we should figure out why" );

【讨论】:

  • 感谢您的回复。我刚刚测试了您的建议,并收到警告说找不到实例方法。
  • 谢谢!原来委托是空的。
猜你喜欢
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2017-09-23
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多