iOS-协议和代理

1,000 阅读1分钟

1.创建一个协议

@protocol newDelete <NSObject>

@required // 必须实现的方法,默认是@required
// 选中cell的代理事件
- (void)changetitle:(NSString *)title;

@optional // 非必须实现的方法
//
- (void)doOther;

@end
  • 谁遵循协议就需要实现协议中的方法。
  • 也可以自己不遵循协议,找个代理人,让代理人去实现协议中的方法。
/**
 * 定义代理,委托其他类来帮助本类完成一些其他任务
 */
@property (nonatomic, weak) id<newDelete>delegate;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //通知代理(如果对应的代理人实现了代理方法,那么,我就把字符串传给他让他使用)
    if ([self.delegate respondsToSelector:@selector(changetitle:)]) {
        [self.delegate changetitle:cell.textLabel.text];
    }
    //
    [self.navigationController popViewControllerAnimated:YES];
遵循协议
<newDelete>

new.delegate = self;

实现协议中的方法
- (void)changetitle:(NSString *)title
{
    NSLog(@"%@",title);
    self.title = title;
}