简单的block
?int multi = 7;
?????? ?
??????? int (^myBlock)(int) = ^(int num){
??????????? return num * multi;
??????? };
??????? int result = myBlock(5);
??????? NSLog(@"結果是:%d",result);
//輸出結果是:
結果是:35
?
void (^printBlock)(NSString *x);
??????? printBlock = ^(NSString* str)
??????? {
??????????? NSLog(@"print:%@", str);
??????? };
??????? printBlock(@"這是個block!");
//輸出結果:
print:這是個block!
?
//字符串數組排序
NSArray *strArr = [NSArray arrayWithObjects:@"abc 02",@"abc 1",@"abc 2", @"abc 21", @"abc 12",@"abc 13",@"abc 15",nil];
??????? NSComparator sortBlock = ^(id str1, id str2)
??????? {
??????????? return [str1 compare:str2];
??????? };
??????? NSArray *Arr = [strArr sortedArrayUsingComparator:sortBlock];
??????? NSLog(@"這個數組是:%@", Arr);
//輸出結果: ??
這個數組是:(
??? "abc 02",
??? "abc 1",
??? "abc 12",
??? "abc 13",
??? "abc 15",
??? "abc 2",
??? "abc 21"
)
//很神奇,竟然默認為10 和 20;如果不加0的話。
static void (^ const blocks)(int) = ^(int i)
??????? {
??????????? if (i > 0) {
?????????????? ?
??????????????? NSLog(@"數字:%d", i);
??????????????? blocks(i - 2);
//??????????????? NSLog(@"shuzi:%d",i);
//??????????????? blocks(i + 2);
??????????? }
??????? };
??????? blocks(10);
?????? ?
//輸出的是 10 8? 6 4 2
注:千萬不能往上加!!
?
??????? int num = 500;
??????? int main(int argc, const char * argv[])
??????? {
??????????? @autoreleasepool {
??????????????? void(^block)(void) = ^(void)
??????????????? {
??????????????????? num++;
??????????????????? NSLog(@"輸出:%d", num);
??????????????? };
??????????????? block();
??????????????? NSLog(@"輸出:%d", num);
??????????? }
??????????? return 0; ?
??????? }
//運行結果:
輸出:501
輸出:501
?
//在代碼塊中改變局部變量編譯不通過,會報錯。要在代碼塊中改變局部變量,需要在局部變量前面加上關鍵字:__block
?__block int local = 500;
??????? void(^block)(void) = ^(void)
??????? {
??????????? local++;
??????????? NSLog(@"local:%d", local);
??????? };
??????? block(); ?
??????? NSLog(@"local:%d", local);
//注:兩個下劃線_+_合成的__block
?
轉載于:https://www.cnblogs.com/wanggang550/p/5166621.html
總結
- 上一篇: jQuery的ajaxFileUploa
- 下一篇: mysqld_multi stop 不能