呼叫协议方法我是相当新的对象 - 和学习有关使用协议和委托。具有多个子视图层次
当我只有两个视图时,我没有遇到下面的示例来实现协议/传递数据,但是,当我有几个子视图时,当我尝试调用某个方法时,出现“无法识别的选择器”错误。
例如,在这样一个场景,我有
- FirstViewController
- SecondViewController
- ThirdViewController
我想ThirdViewController回调到FirstViewController。
通用代码会是这样的:在
FirstViewController.h在firstViewController.m
//present a second controller which will control settings for the app
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"secondViewController" bundle:nil];
secondViewController.delegate= self;
secondViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: secondViewController animated: YES];
@interface FirstViewController : UIViewController <MyProtocol>
后来
-(void) aMethod{
//carry out some action here
}
在secondView
Controller.m或者
//present a third controller...maybe a table view for selecting music
ThirdViewController *thirdViewController = [[ThirdViewController alloc] initWithNibName:@"thirdViewController" bundle:nil];
thirdViewController.delegate= self;
thirdViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: thirdViewController animated: YES];
在ThirdViewContoller.h
//Create a protocol to implement options back on the firstViewController
@protocol MyProtocol;
@interface thirdViewController
{
IBOutlet UIButton *aButton;
}
@property (nonatomic, weak) id<MyProtocol> delegate;
-(IBAction) callMethod:(id)sender;
@end
@protocol MyProtocol <NSObject>
- (void) aMethod;
@end
在ThirdViewController.m
@synthesize delegate;
-(IBAction) callMethod:(id)sender{
[self.delegate aMethod];
}
运行时出现该消息将只发送回secondViewController,而不是到firstViewController因为错误是:
- [SecondViewControlle r aMethod:]:无法识别的选择器发送到实例0x19d620
我认为有一些基本的概念,设置尚未学习,或程序结构错误的代理插座。
有只用两个,在这里工作得很好鉴于代码的例子不胜枚举,但我还没有发现在多个视图很多信息。如果我的程序设计真的不正确,我很抱歉。
它的工作原理!谢谢!!! – ssnytt 2012-03-14 00:17:21
我很高兴这为你工作!如果您发现我的答案令人满意,请考虑将答案标记为“已接受”。 – 2012-03-14 15:30:16