「Objective-C」ios開発でblockを定義、呼び出す方法のまとめ
1.int result = ^(int a){return a*a;}(5);
NSLog(@"—result…%d",result);
2.//Blockポインター
int(^iBlock)(int);
iBlock = ^(int a){ return a+2;};
//呼び出す
int bb = iBlock(10);
NSLog(@"—-bb….%d",bb);
3. //copy処理
static int c = 5;
int (^cBlock)(int) = ^(int ccc){c = 8;return ccc*c;};
NSLog(@"—c…%d",cBlock(2));
4.//"__block"の使い方
__block int v = 0;
int (^vBlock)(int) = ^(int a){ v = 3; return a*v;};
NSLog(@"—abc…%d",vBlock(2));
5.配列
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
int aarrr = ^(int a){[arr removeLastObject]; return a*a;}(2);
NSLog(@"–aarrr…%d—arr…%@",aarrr,arr);
6.関数を定義
typedef void (^myBlock)(int);
@property (nonatomic,assign)myBlock senBlock;
-(void)returnBlock:(myBlock)senderBlocks;
//BTPushViewController
-(void)returnBlock:(myBlock)senderBlocks
{
self.senBlock = senderBlocks;
}
//戻すボタン
– (void)navLeftBtnAction:(UIButton *)btn
{
//blockで値を与える
if (self.senBlock) {
self.senBlock(15);
}
[self.navigationController popViewControllerAnimated:YES];
}
//リダイレクト処理
-(void)doButton
{
BTPushViewController *pushs = [[BTPushViewController alloc] init];
pushs.senBlock = ^(int a)
{
NSLog(@"——–block値%d",a);
};
[self.navigationController pushViewController:pushs animated:YES];
}