《Objective-C高级编程》(二)Block

一、Block简介

带有自动变量的匿名函数,实质就是Objective-C的对象。

1、Block语法

^ returnType paramType expression
^ int (int count) {return count++;}
^ (int count) {return count++;}
^ void (void)  {printf("Hello Block");}
^ {printf("Hello Block");}

2、Block声明

// 函数指针
int (*funcptr) (int)
// Block声明
int (^block) (int)
// Block类型作为函数参数
void func (int (^block) (int))
// Block类型作为属性
@property (nonatomic, copy) void(^block)(void);
// typedef
typedef int (^block) (int)

二、Block实质

1、转换源代码

// 转换源代码指令
clang -rewrite-objc [fileName]
xcrun -sdk iphoneos clang -rewrite-objc ViewController.m
xcrun -sdk iphonesimulator clang -rewrite-objc ViewController.m

源代码

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        void (^JDPBlock) (void) = ^{printf("Hello, Block!");};
        JDPBlock();
    }
    return 0;
}

转换

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
printf("Hello, Block!");}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        void (*JDPBlock) (void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
        ((void (*)(__block_impl *))((__block_impl *)JDPBlock)->FuncPtr)((__block_impl *)JDPBlock);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

可理解为

struct A
struct B, init b
function f(x)

struct X {
A,
B,
constructor(F,B, Flag)
}

x = X(f, b)
x.f(x)

2、Block截获自动变量

源代码

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSInteger integer = 1;
        void (^JDPBlock1) (void) = ^{printf("%lu\n", integer);};
        integer = 2;
        JDPBlock1();
    }
    return 0;
}

转换

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  NSInteger integer;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, NSInteger _integer, int flags=0) : integer(_integer) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  NSInteger integer = __cself->integer; // bound by copy
printf("%d", integer);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        NSInteger integer = 1;
        void (*JDPBlock1) (void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, integer));
        integer = 2;
        ((void (*)(__block_impl *))((__block_impl *)JDPBlock1)->FuncPtr)((__block_impl *)JDPBlock1);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

理解为

struct A
struct B, init b
function f(x) {
i = x.i
}

struct X {
A,
B,
I,
constructor(F, B, I, Flag)
}

i = 1
x = X(f, b, i)
i = 2;
x.f(x)

1、Block语法表达式中使用的自动变量被作为成员变量被添加到结构体中。
2、Block语法表达式中没有使用的自动变量不会被追加。
3、Block截获自动变量值,意味着在定义Block时,Block语法表达式所使用的自动变量值被保存到Block的结构体实例中。
4、Block定义后,自动变量值的修改不会影响到Block内的成员变量的值。

3、__block变量

源代码

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        __block NSInteger integer = 1;
        void (^JDPBlock1) (void) = ^{
            integer = 3;
            printf("%lu\n", integer);
        };
        integer = 2;
        JDPBlock1();
    }
    return 0;
}

3

转换

struct __Block_byref_integer_0 {
  void *__isa;
__Block_byref_integer_0 *__forwarding;
 int __flags;
 int __size;
 NSInteger integer;
};

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __Block_byref_integer_0 *integer; // by ref
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_integer_0 *_integer, int flags=0) : integer(_integer->__forwarding) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  __Block_byref_integer_0 *integer = __cself->integer; // bound by ref

            (integer->__forwarding->integer) = 3;
            printf("%lu\n", (integer->__forwarding->integer));
        }
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->integer, (void*)src->integer, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->integer, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        __attribute__((__blocks__(byref))) __Block_byref_integer_0 integer = {(void*)0,(__Block_byref_integer_0 *)&integer, 0, sizeof(__Block_byref_integer_0), 1};
        void (*JDPBlock1) (void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_integer_0 *)&integer, 570425344));
        (integer.__forwarding->integer) = 2;
        ((void (*)(__block_impl *))((__block_impl *)JDPBlock1)->FuncPtr)((__block_impl *)JDPBlock1);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

理解为

struct Q
struct A
struct B, init b
function f(x) {
q = x.q
q.i = 3
}

struct X {
A,
B,
Q,
constructor(F, B, Q, flag)
}

q = constructor(0, &q, 0, size(Q), 1)
x = X(f, b, q)
q.i = 2;
x.f(x)

三、Block类型

1、Block和__block变量的实质是栈上生成的结构体实例。
2、Block的类型有_NSConcreteGlobalBlock、_NSConcreteStackBlock、_NSConcreteMallocBlock,分别在数据区、栈和堆中。
3、Block不截获自动变量时,就可以将Block设置在程序的数据区中。
4、__block结构体,成员变量__forwarding可以实现无论__block变量配置在栈还是堆上时都能够正确地访问同一个__block变量。
5、ARC有效时,编译器自动将Block从栈复制到堆,何时自动?
5.1、调用Block的copy实例方法时
5.2、Block作为函数返回值返回时
5.3、将Block赋值给附有__strong修饰符的变量时
5.4、在方法名中含有usingBlock的Cocoa框架方法或者GCD的API中传递Block时
6、向方法或函数的参数中传递Block时,编译器不能判断是否自动拷贝,Cocoa usingBlock和GCD除外。

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        void (^JDPBlock) (void) = ^{printf("Hello, Block!");};
        NSLog(@"%@", JDPBlock);
    }
    return 0;
}

<__NSGlobalBlock__: 0x100001050>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSInteger i = 1;
        void (^JDPBlock) (void) = ^{printf("%lu", i);};
        NSLog(@"%@", JDPBlock);
    }
    return 0;
}

// MRC
<__NSStackBlock__: 0x7ffeefbff588>
// ARC
<__NSMallocBlock__: 0x1005969b0>

四、Block&对象

1、Block截获对象

源代码

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        void (^JDPBlock) (void) = ^{NSLog(@"%@", array);};
        JDPBlock();
    }
    return 0;
}

转换

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};

struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  NSMutableArray *array;
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, NSMutableArray *_array, int flags=0) : array(_array) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  NSMutableArray *array = __cself->array; // bound by copy
NSLog((NSString *)&__NSConstantStringImpl__var_folders_yp_b0w71dps58s5rncj_t1znym80000gn_T_main_6313b8_mi_0, array);}
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->array, (void*)src->array, 3/*BLOCK_FIELD_IS_OBJECT*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->array, 3/*BLOCK_FIELD_IS_OBJECT*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        NSMutableArray *array = ((NSMutableArray *(*)(id, SEL))(void *)objc_msgSend)((id)((NSMutableArray *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSMutableArray"), sel_registerName("alloc")), sel_registerName("init"));
        void (*JDPBlock) (void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, array, 570425344));
        ((void (*)(__block_impl *))((__block_impl *)JDPBlock)->FuncPtr)((__block_impl *)JDPBlock);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

理解为

struct A
struct B, init b
function f(x) {
NSMutableArray *array = x.array;
NSLog(@"%@", array);
}

struct X {
A,
B,
NSMutableArray *array;
constructor(F, B, NSMutableArray *array, Flag)
}

NSMutableArray *array = [[NSMutableArray alloc] init];
x = X(f, b, array)
x.f(x)

2、__block修饰对象

源代码

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        __block NSMutableArray *array = [[NSMutableArray alloc] init];
        void (^JDPBlock) (void) = ^{NSLog(@"%@", array);};
        JDPBlock();
    }
    return 0;
}

转换

struct __Block_byref_array_0 {
  void *__isa;
__Block_byref_array_0 *__forwarding;
 int __flags;
 int __size;
 void (*__Block_byref_id_object_copy)(void*, void*);
 void (*__Block_byref_id_object_dispose)(void*);
 NSMutableArray *array;
};

struct __block_impl {
  void *isa;
  int Flags;
  int Reserved;
  void *FuncPtr;
};
struct __main_block_impl_0 {
  struct __block_impl impl;
  struct __main_block_desc_0* Desc;
  __Block_byref_array_0 *array; // by ref
  __main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, __Block_byref_array_0 *_array, int flags=0) : array(_array->__forwarding) {
    impl.isa = &_NSConcreteStackBlock;
    impl.Flags = flags;
    impl.FuncPtr = fp;
    Desc = desc;
  }
};
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
  __Block_byref_array_0 *array = __cself->array; // bound by ref
NSLog((NSString *)&__NSConstantStringImpl__var_folders_yp_b0w71dps58s5rncj_t1znym80000gn_T_main_b13376_mi_0, (array->__forwarding->array));}
static void __main_block_copy_0(struct __main_block_impl_0*dst, struct __main_block_impl_0*src) {_Block_object_assign((void*)&dst->array, (void*)src->array, 8/*BLOCK_FIELD_IS_BYREF*/);}

static void __main_block_dispose_0(struct __main_block_impl_0*src) {_Block_object_dispose((void*)src->array, 8/*BLOCK_FIELD_IS_BYREF*/);}

static struct __main_block_desc_0 {
  size_t reserved;
  size_t Block_size;
  void (*copy)(struct __main_block_impl_0*, struct __main_block_impl_0*);
  void (*dispose)(struct __main_block_impl_0*);
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0), __main_block_copy_0, __main_block_dispose_0};
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        __attribute__((__blocks__(byref))) __Block_byref_array_0 array = {(void*)0,(__Block_byref_array_0 *)&array, 33554432, sizeof(__Block_byref_array_0), __Block_byref_id_object_copy_131, __Block_byref_id_object_dispose_131, ((NSMutableArray *(*)(id, SEL))(void *)objc_msgSend)((id)((NSMutableArray *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSMutableArray"), sel_registerName("alloc")), sel_registerName("init"))};
        void (*JDPBlock) (void) = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, (__Block_byref_array_0 *)&array, 570425344));
        ((void (*)(__block_impl *))((__block_impl *)JDPBlock)->FuncPtr)((__block_impl *)JDPBlock);
    }
    return 0;
}
static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };

理解为

struct Q
struct A
struct B, init b
function f(x) {
q = x.q
NSLog(@"%@", x.array);
}

struct X {
A,
B,
Q;
constructor(F, B, Q, Flag)
}

NSMutableArray *array = [[NSMutableArray alloc] init];
q = Q(0, &q, 0, sizeof(Q), array);
x = X(f, b, q)
x.f(x)

五、Block循环引用

MRC中,__block修饰符被用来避免Block中的循环引用。这是由于当Block从栈复制到堆时,若Block使用的变量为附有__block修饰符的id类型或对象类型的自动变量,不会被retain。若Block使用的变量为没有__block修饰符的id类型或对象类型的自动变量,则被retain。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,504评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,434评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,089评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,378评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,472评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,506评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,519评论 3 413
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,292评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,738评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,022评论 2 329
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,194评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,873评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,536评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,162评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,413评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,075评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,080评论 2 352

推荐阅读更多精彩内容