• IOS protocol 用法


     协议,是通过网络,计算机使用者进行通讯后,互相进行约定规定的集合。两个类进行通讯,用协议就比较方便。下面是 CocoaChina 版主“angellixf”为新手写的协议入门介绍以及代码例子,希望对刚入门开发者有所帮助

    一、说明
      1.协议声明了可以被任何类实现的方法
      2.协议不是类,它是定义了一个其他对象可以实现的接口
      3.如果在某个类中实现了协议中的某个方法,也就是这个类实现了那个协议。
      4.协议经常用来实现委托对象。一个委托对象是一种用来协同或者代表其他对象的特殊对象。
      5:委托,就是调用自己定义方法,别的类来实现。
      6.新特性说明
        @optional预编译指令:表示可以选择实现的方法
        @required预编译指令:表示必须强制实现的方法

    二、定义

    .h
    @protocol ContactCtrlDelegate
    -(void)DismissContactsCtrl;
    @end

    @interface ContactsCtrl : UIViewController {
        id <ContactCtrlDelegate> delegate;
    }
    @property (nonatomic, assign) id <ContactCtrlDelegate> delegate;


    .m
    @synthesize delegate;


    三、例子

    例如:UITextView
    @protocol UITextViewDelegate <NSObject>

    @optional

    - (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
    - (BOOL)textViewShouldEndEditing:(UITextView *)textView;

    - (void)textViewDidBeginEditing:(UITextView *)textView;
    - (void)textViewDidEndEditing:(UITextView *)textView;

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
    - (void)textViewDidChange:(UITextView *)textView;

    - (void)textViewDidChangeSelection:(UITextView *)textView;

    @end

      如果要调用以上这些方法,就必须设置UITextView的委托:TextView.delegate = self;

  • 相关阅读:
    [LeetCode]Valid Parentheses
    LeetCode & Q219-Contains Duplicate II
    LeetCode & Q217-Contains Duplicate-Easy
    LeetCode & Q189-Rotate Array-Easy
    LeetCode & Q169-Majority Element-Easy
    LeetCode & Q167-Two Sum II
    LeetCode & Q122-Best Time to Buy and Sell Stock II-Easy
    LeetCode & Q121-Best Time to Buy and Sell Stock-Easy
    MapReduce工作机制——Word Count实例(一)
    LeetCode & Q119-Pascal's Triangle II-Easy
  • 原文地址:https://www.cnblogs.com/csj007523/p/2601516.html
Copyright © 2020-2023  润新知