2012-06-05 150 views
1

我有三个ViewController; A,B,和C.设置委托给自己的委托?

A给出B,B给出C.

如何从C中传递数据回A?

我设置B的委托A.

BViewController *bvc = [self.storyboard instantiateViewControllerWithIdentifier:@"B"]; 
bvc.delegate = self; 

我罐体C的委托设置为A不知何故?

喜欢:

CViewController *cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"C"]; 
cvc.delegate = (self's parent delegate) 

还是我需要将C的代表设置为B,然后是A?

+0

目前的手段推或模式? –

+0

目前意味着莫代尔,对不起。 – Padin215

+0

我认为你的代码/逻辑存在一些问题。 'bvc.delegate =(self的父代理)'没有意义,它应该是'bvc.delegate = self' ...如果我明白你想要做什么。 –

回答

0

你绝对可以将c的委托设置为a或b。你必须决定绕过b是否有效。 b可能希望在消息回到a之前做些事情,或者可能不在意。所以,如果你是实例C B的内部:

// make b the delegate of c 
cvc.delegate = self; 

// bypass b and make a the delegate of c 
cvc.delegate = self.delegate; 

Ç只需要知道谁的委托是,他们可以在适当的选择作出回应:

// in c 
if ([delegate respondsToSelector:@selector(doSomething)]) 
{ 
    [delegate doSomething]; 
} 

编辑的评论如下: 而不是提出具体到控制器的委托,你能有这样的描述代表一个更通用的协议:

@protocol InfoSelectorDelegate 
- (void)viewController:(UIViewController *)viewController didSelectInfo:(NSDictionary *)info 
@end 

然后既代表将类型:

id<InfoSelectorDelegate> 
+0

我试过这个,但得到一个警告:从不兼容类型'id '分配'id '。 A和B都声明了C的委托:@interface CViewController:UIViewController Padin215

+0

请参阅上面的编辑以获取答案。 – sc0rp10n

+0

好的,为什么委托方法正在使用UIViewController?另外,我只是在每个视图控制器中声明这个协议?我不太理解如何解决这个问题。 – Padin215

2

有无的ViewController C中其代表对B; B设置它的委托A.现在可以有一个方法在B上调用sendMessageToA:因此在C点发送它的委托'sendMessageToA',那么B就可以发送它需要的数据到A。

或者你可以只转发从B到A的消息。因此C将发送它的委托(本例中为B)一条消息。 B说:“我不知道这个消息,让我转发它。” B向A发送消息给A.

这个链接的解释这个概念的一个好工作:http://www.mikeash.com/pyblog/friday-qa-2009-03-27-objective-c-message-forwarding.html