改章节是一篇关于传递声明的帖子
块值传,块类似于C中的函数指针。在Controller中传递数据非常便方,还是续继上一章的例子,将数据从Second传递到First,这里应用块来实现,看起来仿佛和协议很像,不过比协议略单简。
代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/////////// ////////FirstViewController - (void)viewDidLoad { [super viewDidLoad];
self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease]; self.nameLable.textAlignment = UITextAlignmentCenter; self.nameLable.font = [UIFont systemFontOfSize:50]; self.nameLable.textColor = [UIColor blueColor]; [self.view addSubview:self.nameLable];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(130, 170, 60, 40); [button setTitle:@"下一个" forState:UIControlStateNormal]; [button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)pushNext:(id)sender { //初始化second SecondViewController *second = [[SecondViewController alloc]init]; ///用调块 second.send = ^(NSString *str){ self.nameLable.text = str; }; //推过去 [self.navigationController pushViewController:second animated:YES]; [second release]; } |
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
///////////// ////////////SecondViewController.h #import <UIKit/UIKit.h> typedef void (^SendMessage) (NSString *str); ///声明块 @interface SecondViewController : UIViewController<UITextFieldDelegate> @property (nonatomic, copy) SendMessage send; //声明一个块类型属性 @end /////////SecondViewController.m - (void)viewDidLoad { [super viewDidLoad];
UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)]; textFd.borderStyle = UITextBorderStyleRoundedRect; textFd.delegate = self; textFd.tag = 100; [self.view addSubview:textFd]; [textFd release]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; //先断判,在用调块传递实参 if (self.send) { self.send (textField.text); } return YES; } |
文章结束给大家分享下程序员的一些笑话语录: 问路
有一个驾驶热气球的人发现他迷路了。他降低了飞行的高度,并认出了地面 上的一个人。他继续下降高度并对着那个人大叫,“打扰一下,你能告诉我我 在哪吗?”
下面那个人说:“是的。你在热气球里啊,盘旋在 30 英尺的空中”。
热气球上的人说:“你一定是在 IT 部门做技术工作”。
“没错”,地面上的人说到,“你是怎么知道的?”
“呵呵”,热气球上的人说,“你告诉我的每件事在技术上都是对的,但对都没 有用”。
地面上的人说,“你一定是管理层的人”。
“没错”,热气球上的人说,“可是你是怎么知道的?”
“呵呵”,地面上的那人说到,“你不知道你在哪里,你也不知道你要去哪,你 总希望我能帮你。你现在和我们刚见面时还在原来那个地方,但现在却是我 错了”。