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

來源:互聯網
上載者:User

標籤:它的   別人   tom   btn   oid   log   with   nonatomic   property   

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理解及在代理模式中的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.