Block usage in iOS
1. block usage
1. capture the value of the automatic variable
Typedef void (^ TEST) (void );
Int main (int argc, const char * argv []) {
@ Autoreleasepool {
TEST test;
NSString * sample = @ "hello ";
Test = ^ {
NSLog (@ "% @", sample );
};
Sample = @ "name ";
NSLog (@ "% @", sample );
Test ();
}
Return 0;
}
Execution result:
11:55:49. 172 TEST [1262: 303] name
11:55:49. 173 TEST [1262: 303] hello
2. Use of _ block
Typedef void (^ TEST) (void );
Int main (int argc, const char * argv []) {
@ Autoreleasepool {
TEST test;
_ Block NSString * sample = @ "hello ";
Test = ^ {
Sample = @ "what ";
NSLog (@ "% @", sample );
};
Sample = @ "name ";
NSLog (@ "% @", sample );
Test ();
}
Return 0;
}
Execution result:
11:51:02. 532 TEST [120:303] name
11:51:02. 534 TEST [] what
Note that if the _ block keyword is not used, an error occurs during compilation.
3. The address of the intercepted automatic variable
Typedef void (^ TEST) (void );
Int main (int argc, const char * argv []) {
@ Autoreleasepool {
TEST test;
Id array = [NSMutableArray new];
Test = ^ {
NSDictionary * temp = @ {@ "key": @ "value "};
[Array addObject: temp];
NSLog (@ "% @", array );
};
Test ();
}
Return 0;
}
Result: 11:59:05. 941 TEST [1306: 303] (
{
Key = value;
}
)
Note: array is the address of the NSMutableArray object. It is correct to change the address in the block function.
For example:
TEST test;
NSMutableArray * arr = [[NSMutableArray alloc] init];
Test = ^ {
Arr = [[NSMutableArray alloc] init];
};
Test ();
The arr address must be changed, so the compilation is incorrect.
For example:
NSString * str1 = @ "strstr ";
Id array = [NSMutableArray new];
Test = ^ {
Str1 = @ "hello ";
};
Test ();
This is wrong because the address of str1 in the block has changed. At the beginning, it points to the static variable @ "strstr" and now points to the address of the static variable zone @ "hello ".