zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    CF1290E Cartesian Tree
    【LeetCode】11. 盛最多水的容器
    【LeetCode】10. 正则表达式匹配
    【LeetCode】9. 回文数
    【LeetCode】8. 字符串转换整数 (atoi)
    【LeetCode】7. 整数反转
    【LeetCode】6. Z 字形变换
    【LeetCode】5. 最长回文子串
    【LeetCode】4. 寻找两个正序数组的中位数[待补充]
    【LeetCode】3. 无重复字符的最长子串
  • 原文地址:https://www.cnblogs.com/csj007523/p/2601516.html
Copyright © 2011-2022 走看看