iOS學習(OC語言)知識點整理
block 是一種數(shù)據(jù)類型,類似于C語言中沒有名字的函數(shù),可以接收參數(shù),也可以返回值與C函數(shù)一樣被調用
封裝一段代碼 可以在任何地方調用 block 也可以作為函數(shù)參數(shù),以及函數(shù)返回值
1 //定義了一個block類型MyBlock,MyBlock類型的變量只能指向帶兩個int的參數(shù)和返回int的代碼塊 2 typedef int (^MyBlock)(int,int); 3 //定義一個函數(shù)指針 4 int (*pMath)(int ,int); 5 6 int add(int a,int b) 7 { 8 return a+b; 9 }10 11 int sub(int a,int b) 12 { 13 return a-b; 14 }15 16 int main(int argc, const char * argv[]) { 17 @autoreleasepool { 18 pMath = add;//指向函數(shù)指針 19 //NSLog(@"sum: %d",pMath(2,3)); 20 pMath = sub; 21 22 //定義了一個block,block只能指向帶2個int的參數(shù),返回int的代碼塊 23 //以^開始的為代碼塊,后面()是參數(shù),然后{}代碼塊 24 int (^bloke1)(int,int) = ^(int a,int b){ 25 return a+b; 26 };27 28 int s = bloke1(3,5); 29 NSLog(@"s:%d",s); 30 //定義一個block指向沒有參數(shù)沒有返回值的代碼塊(沒有參數(shù),void可以省略) 31 void (^block2)(void) = ^{ 32 NSLog(@"PRograming is fun!"); 33 }; 34 block2(); 35 int (^block3)(int,int) = ^(int a,int b ){ 36 return a-b; 37 38 }; 39 40 //定義了MyBlock類型的變量,賦值代碼塊 41 MyBlock block4 = ^(int a,int b){ 42 return a*b; 43 };44 45 NSLog(@"%d",block4(2,5)); 46 47 int c = 10; 48 __block int d = 1; 49 //block塊可以訪問塊外的變量但是不能修改,如果需要修改,變量前加上__block修飾 50 void (^block5)(void) = ^{ 51 d = d+2; 52 NSLog(@"c:%d,d:%d",c,d); 53 }; 54 block5(); 55 } 56 return 0; 57 }
1 UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(10, 50, 300, 150)];2 [self.view addSubview:imgv];3 4 //使用 __unsafe_unretained 重新定義對象 解決互為強引用的問題5 __unsafe_unretained UIImageView *weakImagev = imgv;6 [imgv setImageWithURL:[NSURL URLWithString:@"http://xxx/xxx.jpg?570x300_120"] withPlaceHolder:nil 7 competion:^(UIImage *image) {8 weakImagev.image = image;9 }];
//將局部變量聲明為__block,表示將會由block進行操作,比如: __block float price = 1.99; float (^finalPrice)(int) = ^(int quantity){ return quantity * price;};int orderQuantity = 10;price =0.99;NSLog(@"With block storage modifier - Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity)); //此時輸出為With block storage modifier – Ordering 10 units, final price is: $9.90
新聞熱點
疑難解答