美文网首页
Apple Documentation <Foundati

Apple Documentation <Foundati

作者: 马大俊不是啥好人 | 来源:发表于2016-12-06 10:16 被阅读17次

在iOS中有个东西叫block,功能的话可以传递参数,封装代码
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);
}

代码中定义了一个无返回值,有参数的block,在ViewDidLoad中对block进行了赋值,把一段代码给予block,这样在调用到block时就会直接执行这段代码。
控制台输出

输出.png

传递参数:

在nnvc中设置vc界面的标签text

设程序从ViewController(vc)跳转到nnViewController(nnvc)

在nnvc.h中声明block以方便vc跳转时调用

#import <UIKit/UIKit.h>
typedef void(^change)(id);
@interface nnViewController : UIViewController
@property(nonatomic,copy) change changeStr;
@end

在nnvc的ViewDidLoad中用self调用声明的block属性

- (void)viewDidLoad {
    [super viewDidLoad];
    self.changeStr(@"DDDDDDDDDDDDD");
    // Do any additional setup after loading the view.
}

在vc中添加touch事件 touchBegin,在begin中初始化nnvc,并获取nnvc的changeStr属性且实现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。

相关文章

网友评论

      本文标题:Apple Documentation <Foundati

      本文链接:https://www.haomeiwen.com/subject/eoolmttx.html