代理的使用

MyView.h

 @protocal ViewTouchDelegate<NSObject>

  @required

  -(void)touchMyView;

 @end

{

  id<ViewTouchDelegate>delegate;

}

@property (nonamtic,assign)id<ViewTouchDelegate>delegate;

-(void)touchMyView;

MyView.m

-(id)init

{

  self =[super init];

  if(self)

       {

NSTimer *timer =[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(touchMyView) userInfo:nil repeats:YES];

        [timer fire];

       }     

  return self;

}

-(void)touchMyView

{

  delegate =_delegate;

  if([_delegate conformsToProtocal:@protocal(ViewTouchDelegate)])

  {

    if([_delegate respondsToSelector:@selector(touchMyView)])

    {

      [_delegate touchMyView];

            }

       }

}

MyViewController.h

#import "MyView.h"

@interface MyViewController:UIViewController <ViewTouchDelegate>

MyViewController.m

-(void)viewDidLoad

{

  [super viewDidLoad];

  MyView *_myView =[[MyView alloc]init];

  _myView.frame =CGRectMake(0,0,100,100);

  _myView.delegate=self;

  [self.view addSubView:_myView];

}

-(void)touchMyView

{

  NSLog(@"Delegate is doing things");

}

原文地址:https://www.cnblogs.com/520myp1314/p/4418262.html