[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
比大多数人的努力程度之低,根本轮不到拼天赋...
宝宝巴士 SD.Team

浙公网安备 33010602011771号