1. 程式人生 > >ios--->OC中Protocol理解及在代理模式中的使用

ios--->OC中Protocol理解及在代理模式中的使用

markdown 全部 interface int n) 遇到 其它 car mailto

OC中Protocol理解及在代理模式中的使用

Protocol基本概念
  • Protocol翻譯過來, 叫做”協議”,其作用就是用來聲明一些方法;
Protocol(協議)的作用
  • 定義一套公用的接口(Public)
    • @required:必須實現的方法,默認在@protocol裏的方法都要求實現。
    • @optional:可選實現的方法(可以全部都不實現)
  • 委托代理(Delegate)傳值
    • 它本身是一個設計模式,它的意思是委托別人去做某事。
    • 比如:兩個類之間的傳值,類A調用類B的方法,類B在執行過程中遇到問題通知類A,這時候我們需要用到代理(Delegate)。又比如:控制器(Controller)與控制器(Controller)之間的傳值,從C1跳轉到C2,再從C2返回到C1時需要通知C1更新UI或者是做其它的事情,這時候我們就用到了代理(Delegate)傳值;
protocol和繼承區別
  • 繼承之後默認就有實現, 而protocol只有聲明沒有實現
  • 相同類型的類可以使用繼承, 但是不同類型的類只能使用protocol
  • protocol可以用於存儲方法的聲明, 可以將多個類中共同的方法抽取出來, 以後讓這些類遵守協議即可
運用實例
//1.定義協議類
#import <UIKit/UIKit.h>
@class XMGCartItem,XMGCartCellTableViewCell;

@protocol XMGCartCellTableViewDelegate <NSObject> // 定義協議
-(void)winecelladdfun:(XMGCartCellTableViewCell *)cell; //協議方法
-(void)winecellreduesfun:(XMGCartCellTableViewCell *)cell;//協議方法

@end

@interface XMGCartCellTableViewCell : UITableViewCell
@property(nonatomic,strong)XMGCartItem *winecell;
@property(nonatomic,weak)id<XMGCartCellTableViewDelegate>delegate;  //協議屬性
@end

//2.協議類中何時調用協議方法
#import "XMGCartCellTableViewCell.h"
#import "XMGCartItem.h"
@interface XMGCartCellTableViewCell ()

@end

@implementation XMGCartCellTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];

}

- (IBAction)reducebtn:(UIButton *)sender {
//開始調用協議方法
    if([self.delegate respondsToSelector:@selector(respondsToSelector:)]){
        [self.delegate winecellreduesfun:self];
    }
}
@end


//3.某類遵守協議並實現協議
@interface XMGCartViewController () <XMGCartCellTableViewDelegate>
@end
    //協議實現
#pragma XMGCartCellTableViewDelegate
-(void)winecelladdfun:(XMGCartCellTableViewCell *)cell
{
    int totalmoney=self.totalmoney.text.intValue + cell.winecell.money.intValue;
    self.totalmoney.text=[NSString stringWithFormat:@"%d",totalmoney];
}

ios--->OC中Protocol理解及在代理模式中的使用