iOS RAC 깔개 Block

2157 단어
너 진짜 Block 쓸 줄 알아?
block ` `
block ` `
block ` ` ( )

강화:

1. Block을 대상으로 하는 속성

Person.h
#import 
@interface Person : NSObject
/* block  arc strong   ARC  copy */
/** block */
@property (nonatomic,copy)  void(^block)();
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person *p = [[Person alloc] init];
    void(^XDBlock)() = ^() {
        
        NSLog(@"XDBlock");
    };
    // 
    // XDBlock();
    p.block = XDBlock;
    _p = p;
    
}
$NSLog:XDBlock

2. Block을 방법의 매개 변수로 한다

Person.h
#import 

@interface Person : NSObject

- (void)eat:(void(^)(NSString *))block;

@end
Person.m
@implementation Person
- (void)eat:(void (^)(NSString *))block{

    block(@"");
}
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
   Person *p = [[Person alloc] init];
    [p eat:^(NSString *a) {
    
        // 
        NSLog(@" %@",a);
    }];

    
}
$NSLog: 

3. Block을 반환값으로 사용하기 (확장성이 매우 강하다)

Person.h
#import 

@interface Person : NSObject

- (void(^)(int))run;

@end
Person.m
@implementation Person
- (void(^)(int))run{
    return ^(int m){
        NSLog(@" %d ",m);
    };
}
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
/** Person *p */
@property (nonatomic,strong) Person *p;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
   Person *p = [[Person alloc] init];
     Person *p = [[Person alloc] init];
//    [p run:3];
     p.run(3);

    
}
$NSLog:2017-06-13 15:08:32.164 Block[30445:3119801]  3 

좋은 웹페이지 즐겨찾기