First, the use of block
1, intercept the value of the automatic variable
typedef void (^test) (void);
int main (int argc, const char * argv[]) {
@autoreleasepool {
test test;
nsstring *[email protected] "Hello";
test=^{
NSLog (@ "%@", sample);
};
[email protected] "name";
NSLog (@ "%@", sample);
test ();
}
return 0;
}
Execution Result:
2014-12-26 11:55:49.172 test[1262:303] name
2014-12-26 11:55:49.173 test[1262:303] Hello
2, the use of __block
typedef void (^test) (void);
int main (int argc, const char * argv[]) {
@autoreleasepool {
test test;
__block nsstring *[email protected] "Hello";
test=^{
[email protected] "what";
NSLog (@ "%@", sample);
};
[email protected] "name";
NSLog (@ "%@", sample);
test ();
}
return 0;
}
Execution Result:
2014-12-26 11:51:02.532 test[1202:303] name
2014-12-26 11:51:02.534 test[1202:303] what
Note If you do not use the __block keyword, an error will be compiled
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 *[email protected]{@ "key": @ "value"};
[Array addobject:temp];
NSLog (@ "%@", array);
};
test ();
}
return 0;
}
results: 2014-12-26 11:59:05.941 test[1306:303] (
{
key = value;
}
)
Description: Array is the Nsmutablearray object address, changing the address in the block function has not changed, so it is correct
if it is as follows:
test test;
nsmutablearray *arr=[[nsmutablearray alloc] init];
test=^{
Arr=[[nsmutablearray alloc] init];
};
test ();
Arr wants to change the address, so the compilation error
If this is the case:
nsstring *[email protected] "strstr";
ID array=[nsmutablearray new];
test=^{
[email protected] "Hello";
};
test ();
This is wrong, because the address of str1 in the block has changed, just beginning to point to the static variable go @ "Strstr", now point to @ "Hello" static variable area address
Detailed usage of block in iOS