protocol 是定义了一些方法而不去实现它,谁遵循协议时,必须实现该协议的方法。
代理设计模式的小例子:
一个StudyDelegat.h的协议,定义一个方法。
<pre name="code" class="objc">#import <Foundation/Foundation.h>
@class Student;@protocol StudyDelegate <NSObject>@required-(void)studyWithStudent:(Student *)student;@end
接着,定义一个Teacher类遵守StudyDelegate这个协议。
Teacher.h 引用代理,并且遵守代理协议。在.m文件将代理方法实现。
#import <Foundation/Foundation.h>
#import "StudyDelegate.h"
@interface Teacher : NSObject<StudyDelegate>
@property(nonatomic,copy)NSString *teacherName;
@end
Teacher.m 下面的代码
#import "Teacher.h"
#import "Student.h"
@implementation Teacher
-(void)studyWithStudent:(Student *)student{
NSLog(@"%@老师教会了 %@",self.teacherName,student.studyCoure);
}
@end
然后定义一个Student类,在类中定义一个必须遵守id<StudyDelegate>的实例变量delegate
在Student的头文件中,引入StudyDlegate的头文件,并且自己定义个协议。在方法-(void)studentStudyIos中,让delegate去调用代理方法并且把自己的传给
代理。
Student.h文件的代码如下
#import <Foundation/Foundation.h>
#import "StudyDelegate.h"
@interface Student : NSObject
@property(nonatomic,copy)NSString *studyCoure;
//id类型是可以指向任何对象的类型.
@property(nonatomic,assign) id<StudyDelegate> delegate;
-(void)studentStudyIos;
@end
Student.m文件代码如下
#import "Student.h"
@implementation Student
-(void)studentStudyIos{
[self.delegate studyWithStudent:self];
}
@end
最后,在一个main.m的文件中,创建他们并且实现之间的赋值和方法。
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Teacher.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu1 = [[Student alloc]init];
stu1.studyCoure = @"IOS高级课程";
Teacher *teacher1 = [[Teacher alloc]init];
teacher1.teacherName = @"李伟";
stu1.delegate = teacher1;
[stu1 studentStudyIos];
//[teacher1 studyWithStudent:stu1];
}
return 0;
}