重要经验五:block作为属性的注意事项

  现代ios应用的开发。不使用GCD和block,效率会减少非常多,在今年3月份之前,我在block的学习和使用方面,精力和经验都明显不足,在SF有个牛逼同事。不仅自己积累了一套库,并且对这个库持续进行更新和维护,其架构能力和代码水平都不错,他的代码中使用了大量的GCD,为了适应这些技术。我在coding的过程中,開始有意识的多写GCD的代码,刚開始一切顺利。直到我使用block来作为一个对象的属性。这让我纠结了非常久。

  我遇到的问题是:1。这样的属性block,其它类在使用的时候,应该怎么写? 2,block的类型不为void、int,而是对象时,比方NSString*时,又应该怎么办?

  这两个非常easy的问题,让我前后一起纠结了2个多小时。以下,我把我的測试代码上上来。希望对遇到相同问题的人,有所帮助。以下直接上代码了。

头文件例如以下,实现文件里不须要实现不论什么代码。

#import <Foundation/Foundation.h>

typedef int(^compareBlock)(int a, int b);

@interface HBTestBlock : NSObject

@property(nonatomic, copy) compareBlock compare;

@property(nonatomic, copy) UIView *(^viewGetter)(NSString *imageName); //注意其返回类型为UIView *

@end

以下这两个函数,展示的是怎样在其它的类中,使用这两个属性。

#pragma mark 測试对象的属性为block

- (void)testObjPropertyBlock

{

    HBTestBlock *objPropertyBlockObj = [[HBTestBlock alloc] init];

    objPropertyBlockObj.viewGetter = ^(NSString *imageName){

//        return [[UIView alloc] init]; //特别注意此处。若对象不匹配,则会报错,设置为nil也会报错。

        return [self currentView];

    };

    objPropertyBlockObj.viewGetter(@"hello"); //实际运行block

}


- (UIView *)currentView

{

    NSLog(@"now I am in currentView");

    return nil;

}


- (void)testPropertyBlock

{

    HBTestBlock *properBlockObj = [[HBTestBlock alloc] init];

    properBlockObj.compare = ^(int a,int b)

    {

        int result = [self maxer:a another:b];

        NSLog(@"the result is %d",result);

        return result;

    };

    NSLog(@"the properBlockObj.compare is %d",properBlockObj.compare(100,200));

}


- (int)maxer:(int)a another:(int)b

{

    if (a > b) {

        return a;

    }

    return  b;

}





posted @ 2017-07-03 14:03  zsychanpin  阅读(557)  评论(0编辑  收藏  举报