此類的例子很多博客都有,只是解釋的都很模糊,看了也還是不明白
第一題: test會(huì)打印什么?因?yàn)樯?
typedef void(^TestBlock)(void);
NSString *test = @"test1111";
NSLog(@"內(nèi)存地址1:%p 指針地址1: %x",test,&test);
TestBlock b2 = ^(void){
NSLog(@"%@",test);
NSLog(@"內(nèi)存地址2:%p 指針地址2: %x",test,&test);
};
test = @"test2222";
b2();
NSLog(@"內(nèi)存地址3:%p 指針地址3: %x",test,&test);
- 答案是test1111
原因:
/*
2019-03-07 15:36:02.437971+0800 OCVoicePro[65484:1357190] 內(nèi)存地址1:0x10b654448 指針地址1: e50af2b8
2019-03-07 15:36:02.438218+0800 OCVoicePro[65484:1357190] test1111
2019-03-07 15:36:02.438354+0800 OCVoicePro[65484:1357190] 內(nèi)存地址2:0x10b654448 指針地址1: 294c0
2019-03-07 15:36:02.438471+0800 OCVoicePro[65484:1357190] 內(nèi)存地址3:0x10b6544c8 指針地址3: e50af2b8
*/
c++block代碼:
static void __QQViewController__viewDidLoad_block_func_0(struct __QQViewController__viewDidLoad_block_impl_0 *__cself) {
NSString *test = __cself->test; // bound by copy
//注釋:拷貝了新的test指針
NSLog((NSString *)&__NSConstantStringImpl__var_folders_xl_5h4m37_n34b2xnc4gxq3z8r80000gn_T_QQViewController_2ba859_mi_1,test);
}
-Block會(huì)對(duì)外部的變量進(jìn)行一次"臨時(shí)“的”拷貝“.產(chǎn)生一個(gè)新的指針,對(duì)象地址不變
第二題: label會(huì)顯示什么字樣?
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 40)];
NSLog(@"內(nèi)存地址1:%p 指針地址1: %x",label,&label);
label.text = @"block作用域外賦值++++";
void (^backValue)(NSString *) = ^(NSString *str) {
label.text = str;
NSLog(@"內(nèi)存地址2:%p 指針地址2: %x",label,&label);
};
backValue(@"block作用域內(nèi)賦值------");
NSLog(@"內(nèi)存地址3:%p 指針地址3: %x",label,&label);
[self.view addSubview:label];
- 答案是block作用域內(nèi)賦值------
原因:
/*
2019-03-07 15:26:52.991643+0800 OCVoicePro[65387:1352714] 內(nèi)存地址1:0x7fb253c1a740 指針地址1: ee08d280
2019-03-07 15:27:25.625023+0800 OCVoicePro[65387:1352714] 內(nèi)存地址2:0x7fb253c1a740 指針地址2: 2bca2a0
2019-03-07 15:27:52.486911+0800 OCVoicePro[65387:1352714] 內(nèi)存地址3:0x7fb253c1a740 指針地址3: ee08d280
*/
c++block代碼:
static void __TTViewController__viewDidLoad_block_func_0(struct __TTViewController__viewDidLoad_block_impl_0 *__cself, NSString *str) {
UILabel *label = __cself->label; // bound by copy
//注釋:拷貝了新的label指針
((void (*)(id, SEL, NSString * _Nullable))(void *)objc_msgSend)((id)label, sel_registerName("setText:"), (NSString *)str);
}
- label的指針同樣被拷貝,label.text = str;的賦值是通過runtime發(fā)送了一個(gè)setText的消息對(duì)label的text屬性進(jìn)行改變.