4

我在 Customer.h 文件中定义了协议,如下所示:

@class Customer; 
@protocol CustomerDelegate <NSObject>

-(void) didSelectCustomer:(Customer *) customer; 

@end

@interface Customer : NSObject
{

}

@property (nonatomic,copy) NSString *name; 
@property (nonatomic,copy) NSString *occupation; 

@end

MasterViewController(左侧)调用 didSelectCustomer 方法,如下所示:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Customer *selectedCustomer = [customers objectAtIndex:[indexPath row]];
    [self.delegate didSelectCustomer:selectedCustomer]; 
}

现在,我需要告诉 DetailViewController(右侧)做某事。DetailViewController 符合 CustomerDelegate 协议。

@interface DetailViewController : UIViewController<UISplitViewControllerDelegate,CustomerDelegate>
{

}

-(void) didSelectCustomer:(Customer *)customer
{
    NSLog(@"sssdasdasdasd");
}

didSelectCustomer 方法永远不会被调用。我想我需要设置 masterViewController.delegate = self 但我不确定在哪里设置这个东西。

更新 1:

我在 DetailViewController 中添加了 MasterViewController 的实例,但它不起作用:

- (void)viewDidLoad
{
    [super viewDidLoad];    

    MasterViewController *master = [[MasterViewController alloc] init];
    master.delegate = self; 
}

解决方案:

在 AppDelegate 中:

  else 
    {
        UISplitViewController *splitViewController = (UISplitViewController *) self.window.rootViewController; 
        splitViewController.delegate = [splitViewController.viewControllers lastObject];



        UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
       // splitViewController.delegate = (id)navigationController.topViewController;




        DetailViewController *detail =(DetailViewController *) [splitViewController.viewControllers lastObject];

        UINavigationController *masterNavigationController = [splitViewController.viewControllers objectAtIndex:0];

        MasterViewController *master = (MasterViewController *)masterNavigationController.topViewController;

        master.delegate = detail; 
    }
4

2 回答 2

0

您永远不会明确地将自己声明为 Consumer 类的委托。仅仅符合它不会削减它。通过创建 Consumer 的实例在 -viewDidLoad 中声明它,可能像这样:

-(void)viewDidLoad {
    Consumer *consumer = [[Consumer alloc]init];
    [consumer setDelegate:self];
}

您也没有在 Consumer 中为您的委托对象声明属性,因此它永远无法真正被访问。首先这样做:

@class Customer; 
@protocol CustomerDelegate <NSObject>

-(void) didSelectCustomer:(Customer *) customer; 

@end

@interface Customer : NSObject
{

}

@property (nonatomic,copy) NSString *name; 
@property (nonatomic,copy) NSString *occupation; 
@property (weak) id <CustomerDelegate> delegate; //use assign or __unsafe_unretained if targeting <5.0.

@end

您可以检查您的课程是否符合您的协议,如下所示:

if (![delegate conformsToProtocol:@protocol(CustomerDelegate)]) {
    [NSException raise:@"Delegate Exception"
                format:@"Parameter does not conform to CustomerDelegate protocol at line %d", (int)__LINE__];
}
于 2012-04-04T21:32:26.133 回答
0

拆分视图控制器的最后一个对象。

此对象返回一个 UI 导航控制器。

你知道,那么你可以自己做。

于 2014-01-20T08:42:30.110 回答