zoukankan      html  css  js  c++  java
  • [Objective-C] 015_Delegate(委托代理)

    Delegate在iOS开发中随处可见,Delegate是一种功能强大的软件架构设计理念,它的功能是程序中一个对象代表另一个对象,或者一个对象与另外一个对象协同工作(如小明喜欢一个女孩如花,却苦于没有如花的联系方式,于是叫好兄弟小东去拿如花联系方式,小东同学一天后返回结果给小明,....)。小明能否成功追到如花,小东在其中又做了些啥事,下面一步步分解。

    1.创建一个Delegate(通过protocol)

    #import <Foundation/Foundation.h>
    @protocol PhoneNumberDelegate <NSObject> @required - (NSString *)goddessPhoneNumber; @end

    2.声明一个Delegate(小明)

    @interface Student : Person <StudentProtocol>
    
    @property (nonatomic, assign) id<PhoneNumberDelegate>delegate;
    - (id)initWithName:(NSString *)name sex:(NSString *)sex age:(int)age;
    @end
    

    3.实现委托代理方法(小东)

    #import "Person.h"
    
    @implementation Person
    @synthesize name = _name,sex = _sex;
    @synthesize age = _age;
    
    - (NSString *)goddessPhoneNumber {
        NSLog(@"正在火速赶往如花家中,向如花妈妈打探如花的号码... 5分钟拿到了. 如花的号码13888888888");
        return @"13888888888";
    }
    @end
    

    4.设置委托代理(小明->小东),并调用代理方法

    #import "AppDelegate.h"
    #import "Person.h"
    #import "Student.h"
    
    @interface AppDelegate ()
    @end
    
    @implementation AppDelegate
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        
        Student *xiaoMing = [[Student alloc] init];
        Person  *xiaoDong = [[Person alloc] init];
        //设置委托代理
        xiaoMing.delegate = xiaoDong;
        //执行委托代理方法
        NSString *phoneNumber = [xiaoDong goddessPhoneNumber];
        //保留女神的号码
        xiaoMing.goddessPhoneNumber = phoneNumber;
        [xiaoDong release]; 
        [xiaoMing release];
    
        return YES;
    }
    @end
    

      

    Delegate就是这么简单好用,小明如愿拿到了如花的号码。

    2015-08-10 21:20:56.516 Attendance[56285:1842177] 正在火速赶往如花家中,向如花妈妈打探如花的号码... 5分钟拿到了. 如花的号码13888888888

    2015-08-10 21:20:56.517 Attendance[56285:1842177] 小明终于拿到了如花的号码:13888888888

     

     

    本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 
    转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4719244.html

     

  • 相关阅读:
    JavaScript怎么让字符串和JSON相互转化
    golang怎么使用redis,最基础的有效的方法
    SmartGit过期后破解方法
    Mac下安装ElasticSearch
    浏览器滚动条拉底部的方法
    git 管理
    MAC远程连接服务器,不需要输入密码的配置方式
    centos6.5下使用yum完美搭建LNMP环境(php5.6) 无脑安装
    【笔记】LAMP 环境无脑安装配置 Centos 6.3
    vs2008不能创建C#项目的解决方法
  • 原文地址:https://www.cnblogs.com/superdo/p/4719244.html
Copyright © 2011-2022 走看看