在ios中,委托模式非常常见,那委托模式是什么?

委托模式是把一个对象把请求给另一个对象处理。

下面见例子:

#import <UIKit/UIKit.h>

@protocol LQIPeople<NSObject>
@required
-(void) eat;
-(void) run;
-(void) walk;

@optional
-(void) speak;

@end

@interface LQPerson : NSObject

@property (assign) id<LQIPeople> peopleDelegate;

-(void) liveADay;

@end
#import "LQPerson.h"

@implementation LQPerson

@synthesize peopleDelegate = _peopleDelegate;
-(void) liveADay{
    NSLog(@"8:00 起床。");

    [self.peopleDelegate eat];
    NSLog(@"8:30 上班。");
    [self.peopleDelegate walk];
    NSLog(@"8:55 来不及。");
    [self.peopleDelegate run];
    NSLog(@"9:20 看到同事");
    if ([_peopleDelegate respondsToSelector:@selector(speak:)]) {
        [_peopleDelegate speak];
    }
}

@end
05-07 15:26