文章一:Objective-C回调机制(delegate, protocol)

转载自:http://blog.sina.com.cn/s/blog_6545eb460100pyjy.html

 Objective-C是只支持单一继承的,当需要创建一个类能表现多个类的特性时,需要采用与Java中很类似的称为协议(Protocol)的方法。如同一个类a,一个类b,两个类签订一个协议p,该p协议规定一个方法c,c的实现在b中,当a需要调用实现c时,并不调用类b,而是声明一个id<p> delegate, 如同a掏出一份协议交给代理商,然后delegate会去找到b,让其完成c这件事。这样的调用更加干净,下面用一个例子具体说明一下:

      
     protocol用法:
            @interface ClassA :ClassB<protocol1, protocol2>
    
     首先先来一个一般情况下的例子,声明一个UIView类:
            @interface myView  :UIView{
            }
            @end
     之后再声明一个protocol,前缀为protocol,没有方法的实现(实现要交给别的类去完成):
           @protocol myViewDelegate
            -(void) Fun1;
            -(void) Fun2;
           @end;
     之后就是代理委托人拉,委托的声明方式如下,我们要在ClassB内使用Fun1方法,但是不需要做声明:
          @interface ClassB :UIViewController<myViewDelegate>
          @end
     
    ClassB实现:
          @implement ClassB
           -init{
                 MyView *view = [[MyView alloc]init];
                 view.delegate = self;
                 self.view = view;
           }
           -(void)Fun1{
           //dostuff,like change navigatorBar blablabla
           }
          @end

    那么怎么在ClassA中使用Fun1呢?需要在ClassA的声明中添加:
         @interface myView  :UIView{
           id<myViewDelegate> delegate;
   }
         @property ...
         @end

    具体实现中时:
         -doSth()
          {
           [delegate Fun1];
          }


文章二:自定义Delegate(协议)的实现与继承

转载自:http://www.iloss.me/?p=663


今天做东西用到了协议,这里在写一下吧

//celltwo类

@interface CellTwo : UITableViewCell {

IBOutlet UIButton *btn;

id delegate;

}

@property (assign) id delegate;

@property (nonatomic,retain) UIButton *btn;

-(IBAction)click:(id)sender;   //按钮响应函数

@end

//协议

@protocol cellItemTwoDelegate

@optional

-(void)onCellItem:(int)index;

@end

这里定义一个类和一个协议,celltwo类里面有一个button。

下面在另外一个类里面要用到celltwo。

@interface AssortController : UIViewController

<cellItemDelegate>{

CellTwo *celltwo;

}

- (void)onCellItem:(int)index{

NSLog(@”onCellItem tag:%d”,index);

}

AssortController使用了cellItemDelegate协议,并且实现了协议里面的函数,然后记得

celltwo.delegate = self;

 

然后当我们点下按钮的时候会调用click,我们在click里面在调用协议定义的函数,

-(IBAction)click:(id)sender{

UIButton *button = (UIButton *)sender;

[delegate onCellItem:button.tag];

}

这样就会打印出来onCellItem tag:%d 这个了, 很简单,类似于C++的重虚函数。