把内部的状态通知给外界,我们可以制定一个变量,然后这个变量从外界来指定,之后我们可以通过变量去通知给外界有什么发生了。
按照上文讲的到新建一个protocol,名字为IPeople
#import <Foundation/Foundation.h> //oc里面的协议相当于java里面的接口 @protocol IPeople <NSObject> -(int)getAge; -(void)setAge:(int)age; -(NSString*)getName; @end
新建一个类文件
Man.h
#import <Foundation/Foundation.h> #import "IPeople.h" #import "ManDelegate.h" @interface Man : NSObject<IPeople> //可以写入多个接口,以逗号(,)隔开 { int _age; } -(id)init; -(int)getAge; -(void)setAge:(int)age; -(NSString*)getName; @property id<ManDelegate> delegate; @end
Man.m
#import "Man.h" @implementation Man:NSObject - (instancetype)init { self = [super init];//相当于java里面的this if (self) { self.delegate=nil; } return self; } -(int)getAge{ return _age; } -(void)setAge:(int)age{ if(age!=_age){ //当age值发生变化时代理执行类 if(self.delegate){ [self.delegate onAgeChange:age]; } } _age=age; } -(NSString*)getName{ return @"Netcorner"; } @end
新建一个delegate类协议
#import <Foundation/Foundation.h> @protocol ManDelegate <NSObject> -(void)onAgeChange:(int)age; @end
主程序为:
#import <UIKit/UIKit.h> #import "AppDelegate.h" #import "Man.h" #import "ManDelegate.h" //实现delegate协议的类 @interface ManListener : NSObject<ManDelegate> -(void)onAgeChange:(int)age; @end @implementation ManListener -(void)onAgeChange:(int)age{ NSLog(@"Age Changed,Current age is %d",age); } @end int main(int argc, char * argv[]) { Man *m=[[Man alloc]init ]; [m setDelegate:[[ManListener alloc]init]]; [m setAge:15]; }