在ios中举个简单的protocol例子,关于两个类用协议方式传值。

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值