在block中,整型变量、字符变量的运行结果和类成员的是不同

No.1 整型变量
int x = 10;
void (^vv)(void) = ^{printf("x is %d\n", x);};
x = 11;
vv();

运行结果:x is 10

No.2 字符变量
NSString* str = @"123";
void (^vv)(void) = ^(void){NSLog(@"str is %@", str);};
str = @"456";
vv();

运行结果:str is 123

No.3 类成员的整型变量
@interface Test : NSObject
{
   int x;
}
@property (nonatomic, assign) int x;
@end

@implementation Test
@end

Test* t = [[Test alloc] init];
t.x = 10;
void (^vv)(void) = ^(void){NSLog(@"t is %d", t.x);};
t.x = 20;
vv();

运行结果:t is 20

No.4 类成员的字符变量
- (void)logInfo
{
   self.name = @"123";
   void (^test)(void) = ^{NSLog(@"%@", self.name);};
   self.name = @"456";
   test();
}

Person* p = [[Person alloc] init];
p.name = @"1111";
void (^vv)(void) = ^(void){NSLog(@"t is %@\n", p.name);};
p.name = @"2222";
vv();

[p logInfo];

运行结果:t is 2222
         456
         
         
今日和前辈一块儿研究后发现:
block在捕获变量的时候只会保存变量被捕获时的状态(对象变量除外),
以后即使变量再次改变,block中的值也不会发生改变


同时,形如如下对常量的赋值在Xcode环境下
NSString* str = @"123";
NSLog(@"p1 = %p", str);
void (^vv)(void) = ^(void){NSLog(@"str is %@", str);};
str = @"456";
NSLog(@"p2 = %p", str);
vv();

p1和p2打印出指针的值是不同的
相关文章
相关标签/搜索