Objective-CでFlashの非同期処理みたいなの
Objective-C で UIViewController を入れ子にしたときに、子UIViewController から親UIViewController の Function を呼びたいとき。
かなり前に書いてたのに、公開忘れてたので今公開。
こーゆーの中々覚えられないアフォーなのでメモ。。。
—————————-
AppDelegate
- ParentController
- ChildController
—————————-
という関係性があると仮定して、このときに ChildController が ParentController のメソッドを呼ぶ場合、
ParentController と ChildController に記述することス。
まず親側の .hファイルには子ファイルの .h ファイルをインポートして @interface 時に Delegate を加える。
// ParentController.h
//
#import <UIKit/UIKit.h>
#import "ChildController.h"
@interface ParentController : UIViewController <ChildControllerDelegate> {
ChildController *childController;
}
@property (nonatomin, retain) ChildController *childController;
// 呼び出される Function を定義
- (void)calledFromChild;
@end
親側の .m ファイルで子の Delegate をセットする
// ParentController.m
//
@implementation ParentController
@synthesize childController;
- (void)calledFromChild {
NSLog(@"calledFromChild");
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated {
ChildController *child = [[ChildController alloc] initWithNibName:@"ChildController" bundle:nil];
self.childController = child;
[self.childController setDelegate:self];
[self.view insertSubview:childController.view atIndex:0];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
@end
次に子側の .h ファイルには protocol で Delegate と @optional で呼び出すメソッドを設定
// ChildController.h
//
#import <UIKit/UIKit.h>
@protocol ChildControllerDelegate;
@interface ChildController : UIViewController {
UIButton *checkButton; // InterfaceBuilder で配置したボタンと仮定
id <ChildControllerDelegate> delegate;
}
@property (nonatomic, retain) IBOutlet UIButton *checkButton;
@property (nonatomic, assign) id <ChildControllerDelegate> delegate;
- (IBAction)clickCheckButton:(id)sender; // InterfaceBuilder で checkButton と関連づける
@end
@protocol ChildControllerDelegate <NSObject>
@optional
- (void)calledFromChild; // ParentController で定義したメソッドと同じ名前
@end
それで子側の .m ファイルで delegate で親側のメソッドを実行
// ChildController.m
//
#import "ChildController.h"
@implementation ChildController
@synthesize checkButton, delegate;
#pragma mark -
// 実際に呼び出すメソッド
- (IBAction)clickCheckButton:(id)sender {
if( [delegate respondsToSelector:@selector(calledFromChild)] )
[delegate calledFromChild];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidUnload {
checkButton = nil;
[super viewDidUnload];
}
- (void)dealloc {
[checkButton release];
[super dealloc];
}
@end
これで、checkButton に関連づけられたボタンにタッチしたときに
Xcode の[実行]-[コンソール]で表示されるウィンドウに「calledFromChild」って表示されます。
子側の処理を待ってから、親側でごにょごにょするときに使える。
CATEGORY
POSTED
jam


COMMENT
0 Comment