MVC通过控制中心C来完成信息的传递。常用的方式有,属性传值、代理传值、单例传值以及通过通知中心传值。
视图对象负责展示数据,通常它不会存储数据。数据存储在控制器中,视图通常会让控制器成为自己的委托,在显示数据时调用其委托中相应地方法。
为了降低类之间的耦合度,经常使用委托模式来进行传值。委托模式涉及到协议。
如下例子:
协议
#import <Foundation/Foundation.h>
@protocol ModifyTitleDelegate <NSObject>
- (void)modifyTitle:(NSString *)title;
@end
AViewController
#import <UIKit/UIKit.h>
#import "ModifyTitleDelegate.h"
@interface AViewController : UIViewController<ModifyTitleDelegate>
@end
#import "AViewController.h"
#import "BViewController.h"
@interface AViewController ()
@end
@implementation AViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnTest setTitle:@"PUSH" forState:UIControlStateNormal];
btnTest.frame = CGRectMake(0, 0, 80, 30);
btnTest.center = self.view.center;
[btnTest addTarget:self action:@selector(pushToNext) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTest];
}
- (void)pushToNext{
BViewController *secondVC = [[BViewController alloc] init];
//属性传值
secondVC.title = @"Second";
//设置代理
secondVC.delegate = self;
[self.navigationController pushViewController:secondVC animated:YES];
}
- (void)modifyTitle:(NSString *)title
{
self.title = title;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
BViewController
#import <UIKit/UIKit.h>
#import "ModifyTitleDelegate.h"
@interface BViewController : UIViewController
@property (assign, nonatomic) id <ModifyTitleDelegate>delegate;
@property (retain, nonatomic) UITextField *myTextField;
@end
#import "BViewController.h"
@interface BViewController ()
@end
@implementation BViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"Test" forState:UIControlStateNormal];
btn.frame = CGRectMake(120, 130, 80, 30);
[btn addTarget:self action:@selector(btnPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(120, 80, 80, 30)];
self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.myTextField];
}
- (void)btnPressed
{
//代理传值
[self.delegate modifyTitle:self.myTextField.text];
[self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)dealloc
{
[_myTextField release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end