iOS Developer

iOS开发学习笔记----objective-c之block初探

2016-04-15  本文已影响58人  氯化钠哦

Block介绍


Block语法定义

*Block变量定义: 返回值(^变量名)(函数参数...)

int (^myBlocks)(int);

*Block函数的创建

myBlocks = ^(int a){
    int result = a * a;
    return result;
}

*Block函数的调用

int ret = myBlocks(10);

typedef int (^MathBlock)(int, int);
MathBlock mulBlock;
mulBlock = ^(int a, int b){
   
        return a * b;
};
NSLog(@"a*b = %d", mulBlock(2, 3));

Block实现对象间通信(保姆与小孩问题)

小孩类:

#import <Foundation/Foundation.h>
@interface Child : NSObject

typedef void(^HandleChildBlock)(Child *);
//小孩的清洁值
@property(nonatomic, assign)NSInteger cleanValue;
//Block的内存管理方式用copy
@property(nonatomic, copy)HandleChildBlock washBlock;

@end
#import "Child.h"

@implementation Child

- (instancetype)init
{
    self = [super init];
    if (self) {
        _cleanValue = 100;
        //定时器,循环调用方法,清洁值减少
        [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(timerAction:)
                                       userInfo:nil
                                        repeats:YES];
    }
    return self;
}

- (void)timerAction:(NSTimer *)timer {
    
    NSLog(@"cleacValue:%lu", _cleanValue);
    _cleanValue--;
    
    if (_cleanValue == 95) {
        //当清洁值为95时,保姆给小孩洗澡
        if (self.washBlock) {
            
            _washBlock(self);
        
        }
        
    }
    
}

@end


保姆类:

#import <Foundation/Foundation.h>
@class Child;

@interface Nanny : NSObject

- (void)washChild:(Child *)child;

@end
#import "Nanny.h"
#import "Child.h"

@implementation Nanny

- (void)washChild:(Child *)child {
    
    child.washBlock = ^(Child *ch){
        //Block代码块
        NSLog(@"保姆给小孩洗澡");
        ch.cleanValue = 100;
        
    };
}
@end
上一篇 下一篇

猜你喜欢

热点阅读