block是ios4.0之后出来的一门新技术,应用也非常广泛,只要我们撑握其使用的翘门,使用其来也是非常简单的,而且它能将传统程序简单化
- #import
-
- @interface
BIDViewController : UIViewController - -
(IBAction)clicked:(UIButton *)sender; - -
(IBAction)secondClicked:(id)sender; - -
(IBAction)thirdClicked:(id)sender; - @property
(retain, nonatomic) IBOutlet UILabel *lb; -
- @end
- #import
"BIDViewController.h" - #import
"FirstViewController.h" - @interface
BIDViewController () - {
-
float (^oneFrom)(float); - }
- @end
-
- @implementation
BIDViewController -
- -
(void)viewDidLoad - {
-
[super viewDidLoad]; -
// Do any additional setup after loading the view, typically from a nib. -
oneFrom=^(float aFloat){ -
float result=aFloat-1.0; -
return result; -
}; - }
-
- -
(void)didReceiveMemoryWarning - {
-
[super didReceiveMemoryWarning]; -
// Dispose of any resources that can be recreated. - }
-
- -
(IBAction)clicked:(UIButton *)sender { -
NSLog(@"%f",oneFrom(10.0)); -
-
-
void(^thirdfrom)(float)=^(float r){ -
NSLog(@"%f",r*5.0); -
}; -
[self changeValue:thirdfrom]; - }
-
- -
(IBAction)secondClicked:(id)sender { -
__block CGFloat height=10.0; -
void(^twoFrom)(float)=^(float t){ -
height+=t; -
}; -
NSLog(@"height is %f",height); -
twoFrom(5.0); -
NSLog(@"height is %f",height); - }
-
- -
(IBAction)thirdClicked:(id)sender { -
FirstViewController* first=[[FirstViewController alloc] init]; -
__block UILabel* blockLb=_lb; -
//回调 -
first.testBlock=^(float r){ -
blockLb.text=[NSString stringWithFormat:@"%f",r]; -
}; -
[self presentModalViewControll er:first animated:YES]; - }
-
- -(void)changeValue:(void(^)(float))from
- {
-
[NSThread sleepForTimeInterval:3.0]; -
from(10.0); - }
- -(void)dealloc
- {
-
-
[_lb release]; -
[super dealloc]; - }
- -
(void)viewDidUnload { -
[self setLb:nil]; -
[super viewDidUnload]; - }
- @end
- #import
-
- @interface
FirstViewController : UIViewController - @property(nonatomic,copy)void(^testBlock)(float);
- -
(IBAction)btnClicked:(id)sender; -
- @end
- #import
"FirstViewController.h" -
- @interface
FirstViewController () -
- @end
-
- @implementation
FirstViewController - @synthesize
testBlock; - -
(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil - {
-
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; -
if (self) { -
// Custom initialization -
} -
return self; - }
-
- -
(void)viewDidLoad - {
-
[super viewDidLoad]; -
// Do any additional setup after loading the view from its nib. - }
-
- -
(void)didReceiveMemoryWarning - {
-
[super didReceiveMemoryWarning]; -
// Dispose of any resources that can be recreated. - }
-
- -
(void)dealloc { -
[super dealloc]; - }
- -
(void)viewDidUnload { -
[super viewDidUnload]; - }
- -
(IBAction)btnClicked:(id)sender { -
if (testBlock) { -
testBlock(4.0); -
} -
[self dismissModalViewControll erAnimated:YES]; - }
- @end