Block
- 用起來像普通的Method
- 可以在Method裡又寫一段Code,並存取在Block之外的所有變數(但是只能Read-Only)。
- 用起來的概念像callback
底下在viewDidLoad這個函式中,
宣告了myBlock這個Block並在裡面呼叫了UIAlertView。
- (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,@"白七"));
}
結果如下相關文章︰
1. Block的使用2-注意事項2. Block的使用3-typedef的使用


沒有留言 :
張貼留言