前兩篇我們提到了Block的使用,
這篇來談談要怎麼簡易的初始化一個Block。
tyepdef float (^MyBlockType)(float,float);
typedef後面的東西,
就是原本在宣告Block的等於的左半部。
使用typeDef後︰
MyBlockType myFirstBlock = // ... ;
這樣子用起來是不是輕鬆多了?
相關文章︰
1. Block的使用12. Block的使用2-注意事項
tyepdef float (^MyBlockType)(float,float);
MyBlockType myFirstBlock = // ... ;
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. ViewController *myView = [ [ViewController alloc] init]; myView.delegate = self; [myView willCallDelegatePrint]; [myView willCallDelegateLog:@"Hello myDelegate"]; NSLog(@"sub viewDidLoad"); int outsideValue = 123; int (^myBlock)(int, NSString*) = ^(int num, NSString* str) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"I am Title" message:str delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Btn1" , nil]; [alert show]; //Block對外面的值只能是ReadOnly return outsideValue; }; outsideValue = 456; NSLog(@"get int: %d",myBlock(567,@"白七")); }
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. ViewController *myView = [ [ViewController alloc] init]; myView.delegate = self; [myView willCallDelegatePrint]; [myView willCallDelegateLog:@"Hello myDelegate"]; NSLog(@"sub viewDidLoad"); __block int outsideValue = 123; int (^myBlock)(int, NSString*) = ^(int num, NSString* str) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"I am Title" message:str delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Btn1" , nil]; [alert show]; //Block對外面的值只能是ReadOnly return outsideValue; }; outsideValue = 456; NSLog(@"get int: %d",myBlock(567,@"白七")); }結果如下
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. ViewController *myView = [ [ViewController alloc] init]; myView.delegate = self; [myView willCallDelegatePrint]; [myView willCallDelegateLog:@"Hello myDelegate"]; NSLog(@"sub viewDidLoad"); int outsideValue = 123; int (^myBlock)(int, NSString*) = ^(int num, NSString* str) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"I am Title" message:str delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Btn1" , nil]; [alert show]; //Block對外面的值只能是ReadOnly return num+outsideValue; }; NSLog(@"get added int: %d",myBlock(567,@"白七")); }結果如下
@protocol <protocol name>//在A.h檔中宣告 @required //在A.h檔中宣告此函式"一定"要被實作 @optional //在A.h檔中宣告此函式"不一定"要被實作
@interface Fraction : NSObject現在我們會改成這樣︰
@interface Fraction (Mathxxx)