当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - setting a delegate to self's delegate?

问题描述:

i have three ViewControllers; A, B, and C.

A presents B, B presents C.

how can i pass data from C back to A?

i set B's delegate to A.

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

bvc.delegate = self;

Can i set C's delegate to A somehow?

like:

CViewController *cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"C"];

cvc.delegate = (self's parent delegate)

?

or do i need to set C's delegate to B, then be to A?

网友答案:

Have viewcontroller C set its delegate to B; B sets its delegate A. There now can be a method on B called sendMessageToA: So at the point C sends its delegate the 'sendMessageToA' then B can send what ever data it needs to A.

Or you can just forward messages from B to A. So C will send its delegate (B in this case) a message. B says "I don't know this message, let me forward it." B sends the message to A.

this link does a good job of explaining the concept: http://www.mikeash.com/pyblog/friday-qa-2009-03-27-objective-c-message-forwarding.html

网友答案:

You can most certainly set c's delegate to a or b. You have to decide if bypassing b is valid. b may want to do things before the message gets back to a, or it may not care. So, if you are instantiating c inside of b:

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

or

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

c simply needs to know that whoever its delegate is, they can respond to the appropriate selector:

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

EDIT FOR COMMENT BELOW: Instead of making the delegate specific to the controller you could make a more generic protocol that describes the delegate:

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

And then both delegates would be of type:

id<InfoSelectorDelegate>
分享给朋友:
您可能感兴趣的文章:
随机阅读: