デリゲートの方法
最近、ブログがどんどん手抜きになっているような気がします。
まぁ、それでも見ていただいている人がいるのはありがたい事です。
今日は久しぶりにソースの公開をしようかと。
大げさすぎでした。ウンチクを公開ですね(^^;
デリゲートのソースを公開しておきます。
ウインドウ遷移をして作業が終わり戻ってきたときに情報を受け取るのってどうやっています?
グローバル変数を何処かに持ってそれで受け渡しをしてませんか?
手っ取り早い方法ではあるのですが、それってオブジェクト指向ではないですよねぇ。
それを解決するのがデリゲートです。デリケートではないです。「ケ」は濁音がついてますよ。
つうことで、いつも通りコメントなしのソースを公開します。(笑
「View-Based Aplication」で新規作成してください。
名称は「DelegateControllViewController」です。
次に追加で「UIViewController subClass」で「With XIB for user Interface」を
チェックして「SecondWindow」を新規作成
ソース名はこちら。
SecondWindowController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>@protocol SecondWindowControllerDelegate;
@interface SecondWindowController : UIViewController {
id <SecondWindowControllerDelegate> delegate;
}@property (nonatomic, assign) id <SecondWindowControllerDelegate> delegate;
- (IBAction)closeButton:(id)sender;
@end
@protocol SecondWindowControllerDelegate
- (void)secondWindowControllerDidFinish:(SecondWindowController *)controller
getData:(NSString*)getData;
@end
SecondWindowController.m
#import "SecondWindowController.h"@implementation SecondWindowController
@synthesize delegate;- (IBAction)closeButton:(id)sender
{
[self.delegate secondWindowControllerDidFinish:self getData:@"test"];
}- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}- (void)viewDidUnload {
[super viewDidLoad];
}- (void)dealloc {
[super dealloc];
}@end
DelegateControllViewController.h
#import <UIKit/UIKit.h>
#import "SecondWindowController.h"@interface DelegateControllViewController : UIViewController <SecondWindowControllerDelegate> {
}
- (IBAction)nextView:(id)sender;@end
DelegateControllViewController.m
#import "DelegateControllViewController.h"@implementation DelegateControllViewController
- (IBAction)nextView:(id)sender {
SecondWindowController *controller = [[SecondWindowController alloc] initWithNibName:@"SecondWindow" bundle:nil];
controller.delegate = self;
[self presentModalViewController:controller animated:YES];
[controller release];
}- (void)secondWindowControllerDidFinish:(SecondWindowController *)controller getData:(NSString*)getData{
NSLog(@"getData : [%@]",getData);
[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}@end
で、SecondWindow「SecondWindow.xib」のIBは
「DelegateControllViewController.xib」のIBは,
作成してください。これで完成。
ボタンを押下すると
新しいウィンドウが出て
ボタンを押下すると
デバッガコンソールに「getData:[test]」とでます。