Iphone 使用块传递值替换委托
我已经阅读了很多关于使用块的积极内容,特别是它通过省略委托调用简化了代码。我发现了在动画结束时使用块而不是代理调用的示例。块示例很简单,但我无法将该示例用于iphone应用程序。例如,我使用委托: h 我用它:Iphone 使用块传递值替换委托,iphone,ios,block,Iphone,Ios,Block,我已经阅读了很多关于使用块的积极内容,特别是它通过省略委托调用简化了代码。我发现了在动画结束时使用块而不是代理调用的示例。块示例很简单,但我无法将该示例用于iphone应用程序。例如,我使用委托: h 我用它: -(void)DidTapOnItemAtIndex:(NSInteger)index { NSLog(@"tap on %d",index); } 如何使用块而不是使用代理我可以得到索引,你可以给出建议并且如果给出好的块类别完成效果很好。我不想使用委托来传递索引,我只想使
-(void)DidTapOnItemAtIndex:(NSInteger)index
{
NSLog(@"tap on %d",index);
}
如何使用块而不是使用代理我可以得到索引,你可以给出建议并且如果给出好的块类别完成效果很好。我不想使用委托来传递索引,我只想使用block来获取索引我想您正在寻找这样的东西:
//implementation for AWActionSheet's method: actionForItem:withBlock:
-(void) actionForItem:(UITapGestureRecognizer*)recongizer withBlock:(void(^)(NSInteger integer)) block {
NSInteger myInt = 0;
//whatever
//callback
block(myInt);
}
电话呢
AWActionSheet* actionSheet;
[actionsheet actionForItem:recognizer withBlock:^(NSInteger integer) {
NSLog(@"myInt: %d", integer);
}];
使用此对象:
这是一个按块初始化和使用对象的简单示例:
//Initialization
MGActionSheet *actionSheet = [[MGActionSheet alloc] initWithTitle:@"Block action sheet!" cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Option 1", @"Option 2", @"Option 3", nil];
//Show with completition block
[actionSheet showInView:self.view withChoiceCompletition:^(int buttonIndex) {
if(buttonIndex == actionSheet.cancelButtonIndex) NSLog(@"Cancelled");
else if(buttonIndex == actionSheet.destructiveButtonIndex) NSLog(@"Destructed");
else {
NSLog(@"Option at index: %d", buttonIndex);
}
}];
完成什么??请你再详细解释一下好吗?对不起,我的英文。我的代码是用delegate,我想使用block来完成相同的效果,代理和块都有不同的工作…是的,但我想在单击按钮后使用block在另一个类中获取索引。我不想使用delegatehmm现在我得到了你的链接将帮助你…它能代替代理吗??我的意思是,当某个操作执行得像我们使用委托和通知可以执行的那样时,一个方法如何在另一个类中调用???我想知道我很难理解你的问题。它不应该代替代表。通过这段代码,您可以从object1在object2中执行一个方法,当它完成对object1调用另一个方法(回调)并从object2传递参数时。是的,这正是我想告诉@penwang的,但他没有得到。。。。顺便说一句,我还没问:)谢谢way@theTiger是正确的,您的方法只传递值,但不符合我的问题,对不起我的英语。我不仅获取索引,还执行一些操作来获取方法。例如alertView有两个“确定”按钮和“取消”按钮,当我单击“取消”按钮时,我得到的索引=0,我还可以做一个动作我真的不知道你的意思。在回调块中,您可以执行任何想要的操作。
AWActionSheet* actionSheet;
[actionsheet actionForItem:recognizer withBlock:^(NSInteger integer) {
NSLog(@"myInt: %d", integer);
}];
//Initialization
MGActionSheet *actionSheet = [[MGActionSheet alloc] initWithTitle:@"Block action sheet!" cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Option 1", @"Option 2", @"Option 3", nil];
//Show with completition block
[actionSheet showInView:self.view withChoiceCompletition:^(int buttonIndex) {
if(buttonIndex == actionSheet.cancelButtonIndex) NSLog(@"Cancelled");
else if(buttonIndex == actionSheet.destructiveButtonIndex) NSLog(@"Destructed");
else {
NSLog(@"Option at index: %d", buttonIndex);
}
}];