我读过很多关于使用 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/