在iOS中有個(gè)東西叫block鸠真,功能的話可以傳遞參數(shù)诗宣,封裝代碼
and so on膘怕。。召庞。岛心。
block格式
返回值類型(^block名)(形參s) = ^(形參s) {};
封裝代碼:
#import "ViewController.h"
void(^demoBlock)(NSInteger count);
@interface ViewController ()
@end
@implementation ViewController
@synthesize lab;
- (void)viewDidLoad {
[super viewDidLoad];
demoBlock = ^(NSInteger count)
{
NSInteger sum = 0;
for (int i = 0; i <=count; i++) {
sum+=i;
NSLog(@"%ld",(long)sum);
}
};
demoBlock(10);
}
代碼中定義了一個(gè)無返回值,有參數(shù)的block篮灼,在ViewDidLoad中對(duì)block進(jìn)行了賦值忘古,把一段代碼給予block,這樣在調(diào)用到block時(shí)就會(huì)直接執(zhí)行這段代碼诅诱。
控制臺(tái)輸出
傳遞參數(shù):
在nnvc中設(shè)置vc界面的標(biāo)簽text
設(shè)程序從ViewController(vc)跳轉(zhuǎn)到nnViewController(nnvc)
在nnvc.h中聲明block以方便vc跳轉(zhuǎn)時(shí)調(diào)用
#import <UIKit/UIKit.h>
typedef void(^change)(id);
@interface nnViewController : UIViewController
@property(nonatomic,copy) change changeStr;
@end
在nnvc的ViewDidLoad中用self調(diào)用聲明的block屬性
- (void)viewDidLoad {
[super viewDidLoad];
self.changeStr(@"DDDDDDDDDDDDD");
// Do any additional setup after loading the view.
}
在vc中添加touch事件 touchBegin髓堪,在begin中初始化nnvc,并獲取nnvc的changeStr屬性且實(shí)現(xiàn)block
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
nnViewController* vc = [[nnViewController alloc]init];
vc.changeStr = ^(NSString* str)
{
self.lab.text = str;
};
[self.navigationController pushViewController:vc animated:YES];
}
it's done娘荡。