呼叫協議方法我是相當新的對象 - 和學習有關使用協議和委託。具有多個子視圖層次
當我只有兩個視圖時,我沒有遇到下面的示例來實現協議/傳遞數據,但是,當我有幾個子視圖時,當我嘗試調用某個方法時,出現「無法識別的選擇器」錯誤。
例如,在這樣一個場景,我有
- 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