1.代理的使用方法
定义协议:
/**
* 定义协议,将需要实现的方法列在其中
* 协议名字最好为类名+Delegate,方法名最好以类名开头
* 其中<NSObject>为基协议,遵守本协议时则同时获得基协议中的方法
*/
@protocol tableViewCellDelegate <NSObject>
- (void)tableViewCellDidClickPlusButton:(tableViewCell *)cell;
- (void)tableViewCellDidClickMinusButton:(tableViewCell *)cell;
@end
声明代理属性:
/** 声明代理属性,代理属性必须为weak类型,<>中为协议名 */
@property (weak, nonatomic) id <tableViewCellDelegate> delegate;
调用代理方法:
/**
* 调用可以先判断是否设置了代理对象(self.delegate)
* 以及是否实现了代理方法([self.delegate respondsToSelector:@selector(方法名)])
* 以避免不必要的错误,尤其是当协议方法为可选(optional)时
*/
if (self.delegate && [self.delegate respondsToSelector:@selector(tableViewCellDidClickPlusButton:)]) {
[self.delegate tableViewCellDidClickPlusButton:self];
}
设置代理对象:
/** 声明遵守tableViewCellDelegate协议 */
@interface ViewController () <tableViewCellDelegate>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"ID";
FoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[FoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
/** 设置代理对象为self */
cell.delegate = self;
return cell;
}
实现代理方法:
/** 实现代理方法 */
- (void)tableViewCellDidClickPlusButton:(tableViewCell *)cell
{
NSLog(@"%s", __func__);
}
- (void)tableViewCellDidClickMinusButton:(tableViewCell *)cell
{
NSLog(@"%s", __func__);
}