Block usage in iOS

Source: Internet
Author: User

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 ".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.