本人iOS新手一枚,剛自行學習了下的block,哪裏不對的地方,請指出
例舉1:block的簡單使用
void無返回值,^(myFirstBlock)命名,()無類型
void (^myFirstBlock)() = ^{
NSLog(@"this is a block");//這裏寫需要實現哪些功能
};
例舉2:block的簡單使用
int返回值類型,int a,int b 傳參的類型,這裏返回爲a+b的int類型
int (^addBlock)(int a,int b) = ^(int a,int b){
return a + b;
};
然後在想用的地方調用一下,傳遞a和b參數
int add = addBlock(2,3);
NSLog(@"add=%d",add);
ps:輸出結果add=5
例舉3:block的簡單使用
block內部需要修改數值
NSArray *arr = @[@"dog",@"cat",@"cow",@"pig"];
__block BOOL isExist = NO;//這裏需要在前面加上 __block
//枚舉arr數組查詢
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj compare:@"cow"] == NSOrderedSame){ //NSOrderedSame 表示前者和後者完全一樣
isExist = YES;
}
}];
if (isExist) {
NSLog(@"存在");
}else{
NSLog(@"不存在");
}
例舉4:block用於反向傳值
兩個控制器 控制器1 和 present出來的第二個控制器2
控制器2代碼 .h 裏面
typedef void(^myBlock) (NSString *msg);//定義一個block,myBlock,用於傳遞 NSString類型 的信息
#import <UIKit/UIKit.h>
@interface nextViewController : UIViewController
@property (nonatomic,copy)myBlock msgBlock;//重命名了block
@end
控制器2代碼 .m 裏面,在返回上一個頁面(控制器1)的按鈕裏傳遞參數
- (IBAction)backBtnClick:(UIButton *)sender {
ViewController *VC = [[ViewController alloc] init];//實例化上一個頁面
if (self.msgBlock) {
self.msgBlock(@"我來自第二個頁面"); //傳遞參數
}
[self dismissViewControllerAnimated:VC completion:^{}];
}
然後,控制器1 .m代碼
在彈出第二個頁面(控制器2)的方法裏面調用block(這裏就是控制器2傳遞回來的參數)
- (IBAction)nextBtnClick:(UIButton *)sender {
nextViewController *nextVC = [[nextViewController alloc] init];
nextVC.msgBlock = ^(NSString *msg){
NSLog(@"這裏要得到第二個頁面的文字-------%@",msg);
};
[self presentViewController:nextVC animated:YES completion:^{}];
}
ps:打印結果:這裏要得到第二個頁面的文字-------我來自第二個頁面
反向傳值還是很普及的,這都是很簡單的用法,block裏面不要強引用,記得用__weak修飾,先寫到這裏,後期再添加block相關的新內容