aBigRoybot

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

可能标题有些拗口, 我想表达的是这样一个意思:

有一组方法被若干个类所实现, 但是在这些方法中所要调用到的数据/方法并不是在一个类中的, 比如有三个controller里的button都要实现- (void) buttonPress: 这个方法, 并且都要用到自己controller中的自定义方法, 然后再利用- (void) buttonPress:这个方法反馈一些共同的操作.

基于上面的需求, 我们很自然的想到了protocol, 解决方案如下:

定义一个protocol, 包含- (void) buttonPress: 方法, 这个方法将被定义到TableViewControll里面, 并且会要调用一个TableViewControll的方法, 之后再执行aClassWithButtonMethodDelegate里面的一些相同的代码(也可能在这里面调用了一些aClassWithButtonMethodDelegate私有的变量), 因此在aClassWithButtonMethodDelegate中, 我们声明了一个id<buttonMethodDelegate> _delegate, 用它来调用TableViewControll中定义的buttonPress, 这杨便可以调用到TableViewDelegate中的一些自定义变量和方法.

  

@protocol buttonMethodDelegate<NSObject>
@optional
- (void) buttonPress;
@end

@interface aClassWithButtonMethodDelegate{
     id<buttonMethodDelegate> _delegate;
}

- (void) useButtonPressWithDelegate: (id<buttonMethodDelegate>) aDelegate;
@end

@implement aClassWithButtonMethodDelegate
- (void) useButtonPressWithDelegate: (id<buttonMethodDelegate>) aDelegate{
     self->_delegate = aDelegate;
     if([self->_delegate responseToSelector: @selector(buttonPress)])
           [self->_delegate buttonPress];
}
@end

@interface TableViewControll<buttonMethodDelegate>
- (void) printInfo;
@end
@implement TableViewControll
- (void) printInfo{
   NSLog(@"This is a method from TableViewControll class.");
} 
- (void) buttonPress{
   NSLog(@"buttonPress method has been invoked.");
   [self printInfo]; 
}
@end

  

posted on 2011-11-23 17:58  aBigRoybot  阅读(246)  评论(0编辑  收藏  举报