以下の単純なプロトコルとプロパティの例:
---> ViewController.h ファイル
#import <UIKit/UIKit.h>
#import "MyVC.h"
@interface ViewController : UIViewController<MyVCProtocol>
{
IBOutlet UILabel *label;
IBOutlet UIButton *btnPush;
MyVC *vc;
}
-(IBAction)Buttonclicked;
@end
---> ViewController.m ファイル
#import "ViewController.h"
@implementation ViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(IBAction)Buttonclicked
{
vc = [[MyVC alloc]initWithNibName:@"MyVC" bundle:nil];
vc.delegate=self;
[self.navigationController pushViewController:vc animated:YES];
}
-(void)GetText:(NSString *)text
{
label.textAlignment=UITextAlignmentCenter;
label.text=text;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
---> MyVC.h ファイル
#import <UIKit/UIKit.h>
@protocol MyVCProtocol <NSObject>
-(void)GetText:(NSString *)text;
@end
@interface MyVC : UIViewController
{
IBOutlet UITextField *m_TextField;
IBOutlet UIButton *m_Button;
id <MyVCProtocol> delegate;
}
@property(nonatomic, retain)id <MyVCProtocol> delegate;
-(IBAction)ButtonClicked;
@end
---> MyVC.m ファイル
#import "MyVC.h"
@implementation MyVC
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(IBAction)ButtonClicked
{
[delegate GetText:m_TextField.text];
[self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end