欢迎光临
我们一直在努力

block基本5种yong使用的demo,通过别人的总结http://fuckingblocksynt…

建站超值云服务器,限时71元/月

block基本5种yong使用的demo,通过别人的总结http://fuckingblocksynt...

项目介绍:

block的5种基本用法的总结;适合初学者
As a local variable
As a property:
As a method parameter:
As an argument to a method call:
As a typedef:demo写的很low,希望大家好的建议

[Objective-C] 查看源文件 复制代码

控制器一
#import "ViewController.h"
#import "SecondViewController.h"

@interface ViewController ()

@property (nonatomic,copy) int (^FirstBlock)(int ,int);

@end

@implementation ViewController

- (void)viewDidLoad {
   
    [super viewDidLoad];
   
   
    self.FirstBlock = ^int(int a,int b){
        
        return a + b;
        
    };

}

/*
* 1.作为本地变量
As a local variable:
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
*/
- (IBAction)localVariable:(id)sender{
   
   
   __block int sum ;
   
    int (^myBlock)(int,int) = ^int(int a ,int b){
     
        sum = a +b;
        return sum;
   
    };

    NSLog(@"这是作为本地变量的----%d",myBlock(1,2));

}


/*
* 2. As a property:
    @property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
*/
- (IBAction)asAproperty:(id)sender {
   
    NSLog(@"这是作为属性的----%d",self.FirstBlock(2,3));
   
}

/*
* 3.作为方法参数
As a method parameter:
*/
- (IBAction)Asmethodparameter:(id)sender {
   
   
    NSLog(@"作为方法参数被调用----%d",[self testMethodwithBlock:^int(int a, int b) {
        

        NSLog(@"http://fuckingblocksyntax.com/ a = %d,b = %d",a,b);
         return a * b -b;
  
     }]);
}


/*4.作为方法传递
*As an argument to a method call:
*/

- (int)testMethodwithBlock:(int(^)(int a,int b))MehtodBlock{
   
    //这个可能是传过来的参数
   
      __block  int i = 10;
   
    int sum = 0;
    if (MehtodBlock) {
        
        sum = MehtodBlock(i,2*i);
        
    }
    return sum;

}





- (IBAction)presentSecondVC:(id)sender {
   
   
     SecondViewController *secondVC = [[SecondViewController alloc]init];
   
    secondVC.block = ^(id acolor){
      self.view.backgroundColor = acolor;

    };
   
   
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:secondVC];
   
    [self presentViewController:nav animated:YES completion:nil];
   
   
   
}

控制器二
#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {
   
    [super viewDidLoad];
    self.title = @"这是第二个页面";

   
   
}
- (IBAction)gotoFirstVC:(id)sender {
   

    if (self.block) {
        
        self.block([UIColor redColor]);
        
    }
   
   
    [self dismissViewControllerAnimated:YES completion:nil];
   
}







testBlock.zip
(66.95 KB, 下载次数: 322)

2016-8-29 23:47 上传
点击文件名下载附件

block的5种使用


推荐:
PYPhotosView 用法简单的呈现一组图片的框架(高仿QQ/微信)

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » block基本5种yong使用的demo,通过别人的总结http://fuckingblocksynt…
分享到: 更多 (0)