您的位置:首页 > 移动开发 > IOS开发

iOS Block的使用

2015-11-11 16:52 417 查看
直接上代码:
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface RootViewController :
UIViewController
@end

#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super
viewDidLoad];
// 无参数
无返回值的block 打印一条语句
void(^myBlock)() = ^void{
NSLog(@"11");
};
myBlock();
// 有参数
有返回值 两个整数相加
int (^sum) (int,int) = ^(int a,
int b){
return a + b;
};
int s = sum(1,2);
NSLog(@"%d",s);
UIButton *button = [UIButton
buttonWithType:UIButtonTypeCustom];
button.frame =
CGRectMake(20,
100, 100,
50);
[button setTitle:@"点我呀"
forState:UIControlStateNormal];
button.backgroundColor = [UIColor
magentaColor];
[button addTarget:self
action:@selector(jumpTo:)
forControlEvents:UIControlEventTouchUpInside];
[self.view
addSubview: button];
}
- (void)jumpTo:(UIButton *)button
{
SecondViewController *second = [[SecondViewController
alloc] init];
//接收Block回调的值
second.sendMessage = ^(NSString *name,NSString *address){
//()里面的两个参数
就是传回来的值
NSLog(@"%@",name);
//修改按钮上的文字
//会造成引用计数加1
__block
UIButton *tempButton = button;//避免造成引用计数加1的方式
[tempButton setTitle:name
forState:UIControlStateNormal];
};
[self.navigationController
pushViewController:second
animated:YES];
}
- (void)didReceiveMemoryWarning {
[super
didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//***********************************************************************//

#import <UIKit/UIKit.h>
@interface SecondViewController :
UIViewController
#pragma mark --Block属性 copy修饰
(block本身会在栈区
用copy是它存在堆区
安全操作)
@property(nonatomic,copy)void(^sendMessage)(NSString
*name,NSString *address);
@end

#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super
viewDidLoad];
self.view.backgroundColor = [UIColor
whiteColor];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem
alloc] initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:self
action:@selector(backTo)];
}
- (void)backTo
{
self.sendMessage(@"尼玛傻B二百五",@"屌丝");
[self.navigationController
popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super
didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: