iphone - 使用 block 替换委托(delegate)来传递值

标签 iphone ios block

我读过很多关于使用 block 的积极的事情 - 特别是它通过消除委托(delegate)调用来简化代码。我发现了在动画结束时使用 block 而不是委托(delegate)调用的示例。 block 示例很简单,但我无法将示例用于 iPhone 应用程序。例如,我使用委托(delegate):

.h

@protocol AWActionSheetDelegate <NSObject>

- (int)numberOfItemsInActionSheet;
- (AWActionSheetCell*)cellForActionAtIndex:(NSInteger)index;
- (void)DidTapOnItemAtIndex:(NSInteger)index;

@end

@interface AWActionSheet : UIActionSheet

   @property (nonatomic, assign)id<AWActionSheetDelegate> IconDelegate;
-(id)initwithIconSheetDelegate:(id<AWActionSheetDelegate>)delegate ItemCount:(int)cout;
@end

.m

- (void)actionForItem:(UITapGestureRecognizer*)recongizer
{

   [IconDelegate DidTapOnItemAtIndex:cell.index];

}

我用它:

 -(void)DidTapOnItemAtIndex:(NSInteger)index
{
    NSLog(@"tap on %d",index);

}

如何使用 block 而不是使用委托(delegate)我可以获得索引,您能给建议吗?如果给出好的 block 类别来完成效果非常好。我不想使用委托(delegate)来传递索引,我只想使用 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);
}];

关于iphone - 使用 block 替换委托(delegate)来传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15942974/

相关文章:

ios - 未设置表格的动态高度

ruby - block 内的 def 函数能完成什么任务?

ruby - 在 Block (self) Ruby 中获取 Block 的名称

iphone - 电子邮件验证 iPhone SDK

ios - UICollectionView 中的单元格重叠

iphone - 使 textAlignment 在 UITableViewCellStyleSubtitle 中居中的解决方法

iphone - 旧金山字体未在 Apple Watch 模拟器中显示

ios - 如何强制 View Controller 调用 preferredFocusView?

ios - 无法写入 containerURLForSecurityApplicationGroupIdentifier?

iOS : instance variable in block