【问题标题】:delegate and protocol not working correctly委托和协议无法正常工作
【发布时间】:2012-06-06 01:58:19
【问题描述】:

我正在尝试将数据从一个 TabBarViewController 传递回我的 MasterViewController,但是当我想将数据传递回 MasterViewController 时,我的协议/委托中的方法永远不会被访问。

这就是我所做的 - 我有一个 TabBarViewcontroller 和一个 MasterViewController,TabBarController 作为子视图添加到 MasterViewController ......然后我要做的是将另一个子视图加载到 MasterViewController 上,我打算在我调用的 tabBarViewController 中选择一个 tabbarbutton 时执行我的协议/委托方法。为此,我使用以下代码。 (我希望到目前为止这是有道理的)

TabBarViewController.h

@class MasterViewController;

@protocol LoadActionView <NSObject>
@required
- (void) loadViewsAction;
@end

@interface TabBarViewController : UIViewController <UITabBarDelegate> {


    __weak id <LoadActionView> delegate;

//..
}

@property (weak, nonatomic) id delegate;

//..

TabBarViewController.m

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    switch (item.tag) {
        case 0:
        {
             NSLog(@"item 1 selected");
            [[self delegate] loadViewsAction]; //the thread defiantly makes it here as I have debugged to this point
        }
//..

那么, MasterViewController.h

 #import <UIKit/UIKit.h>
    #import "TabBarViewController.h"

    @interface MasterViewController : UIViewController <UINavigationControllerDelegate, LoadActionView> {


TabBarViewController *tbVC;

}

@property (nonatomic, strong) TabBarViewController *tbVC;
    //..

MasterViewController.m

#import "TabBarViewController.h"

@synthesize tbVC;
    //..

- (void) viewDidLoad {
//..

tbVC = [[TabBarViewController alloc] initWithNibName:@"TabBarViewController" bundle:[NSBundle mainBundle]];
    UIView *tbView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 367.0, 320.0, 49.0)];
    [tbView addSubview:tbVC.view];
    [otherNav.view addSubview:tbView];


}

    - (void) loadViewsAction
    {
        NSLog(@"HITME!"); //threads not making it here.
    }

我通常在这里做的唯一不同的事情是这个 TabBarViewController 被添加为子视图。 .

任何帮助将不胜感激。

【问题讨论】:

  • 你分配loadActionView.delegate = self;在 MasterViewController 中?
  • 哦,不,我没有……但是只是尝试在 MasterViewController 的 viewDidLoad 方法中执行此操作,它给了我这个错误 Use of undeclared identifier 'loadActionView'
  • @xingzhi.sg 不确定您是否看到我的最后一条消息,但尝试执行您说的代码似乎不起作用。
  • @xingzhi.sg 假设您的TabBarController 实例在MasterViewController 中被命名为loadActionView。您需要将其替换为您在代码中使用的名称。请更新您的问题以包含初始化TabBarController 实例的代码。
  • @DavidAlber 是的,我已经添加了调用 TabBarControllerView 的代码行

标签: iphone ios uiviewcontroller delegates protocols


【解决方案1】:

你可以通过添加来调试问题:

NSAssert (nil != [self delegate]);

就在致电loadViewsAction 之前。该断言将失败,因为您尚未分配 TabBarController 的委托。创建 TabVarController 后,执行:

tbVS.delegate = self;

然后,您将拥有一个用于 loadViewsAction 的委托。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多