【IOS学习】Objective-C 协议,以及demo

协议:类似于C++纯虚基类,提供方法,由其他类实现。

委托:类似于java的接口,接口定义了方法,由其他的类申明实现接口,并实现接口。
委托实际上是一个过程、一种实现方式,由另一个类来完成一个类的操作

可以参照此贴查看委托的另类实现
http://blog.csdn.net/zhuiyi316/article/details/7818149
但是可以看到那种实现是通过类作为另一个类的属性完成的

OC的协议实际上是为了解耦而产生的,目的就是为了让程序更加简单,容易扩充

@protocol textSendDelegate;
@interface NextVC : UIViewController
// 协议的实例
@property (nonatomic,assign)id<textSendDelegate> delegate;

@end

// 协议的声明
@protocol textSendDelegate <NSObject]]>
//一定要实现的
@required
-(void)textSend:(NSString *)textString;
//可选实现
@optional
-(void)logOfTextSend;
@end

// 协议方法的触发
if (self.delegate && [self.delegate respondsToSelector:@selector(textSend:)]) {
        [self.delegate textSend:_myTextField.text];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(logOfTextSend)]) {
        [self.delegate logOfTextSend];
    }

// 申明协议实现
@interface RootVC : UIViewController<textSendDelegate>

//协议的绑定
    NextVC *next = [[NextVC alloc]init];
    next.delegate =self;


// 协议实现
-(void)textSend:(NSString *)textString
{
    self.displayLabel.text = textString;
}

-(void)logOfTextSend
{
    NSLog(@"a text is send to RootVC");
}

详细代码参照: https://github.com/caigee/iosdev_sample 下的
DelegateSample


你可能感兴趣的:(ios,协议,类别)