概念:委托模式顾名思义就是是把一个对象把请求委托给另一个对象处理。
2.接下来谈谈ios自带的api中的一些委托的使用,简单谈下tableview的吧
作用:其实ios自带的api很多都是使用委托模式的,如果不理解委托模式的话,我们就很难顺手的使用那些api,而自定义协议之后使用委托,可以让我们方便的处理。
其实ios中的委托机制有点类似于回调机制以及监听器机制。
1、使用协议自定义委托方法以及使用
首先,我们需要使用到@protocol定义协议,该协议中使用@required和@optional定义该协议的方法,两者的区别是前者定义的是其他类遵守协议之后必须得实现的方法,而后者的是随你要不要实现方法都行。
#import <UIKit/UIKit.h>
//用一个@protocol @end 定义协议,定义中使用@required定义的方法的遵守协议之后必须实现的,用@optional的方法使用的协议是随用户要不要实现的
@protocol People<NSObject>
@required
-(void) eat;
-(void) run;
-(void) walk;
@optional
-(void) speak;
@end
//编写类的方法
@interface Person : NSObject
@property (assign) id<People> delegate;
-(void) liveADay;
@end
定义完之后,我们就要来实现那些方法了
#import "Person.h"
@implementation Person
-(void) liveADay
{ //使用委托方法调用delegate中的方法
[self.delegate eat];
[self.delegate walk];
[self.delegate run];
//因为speak方法是随用户要不要实现的,所以要判断下该delegate有无实现该方法。
if ([_delegate respondsToSelector:@selector(speak)]) {
[_delegate speak];
}
}
@end
2.接下来谈谈ios自带的api中的一些委托的使用,简单谈下tableview的吧
一般我们实现tableview的话,都需要在@interface中实现UITableViewDataSource和UITableViewDelegate这两个协议
@interface WKTableVC : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
之后在@implementation中实现协议的方法
@implementation WKTableVC
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
//遵守协议之后,会自动执行以下的方法,即可实现tableview的数据绑定等操作。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
}
<pre name="code" class="objc">- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
@end