协议可选方法在未实现时崩溃



>我正在使用协议和一些可选方法

#import <UIKit/UIKit.h>
@class TextViewTableViewCell;
@protocol TextViewTableViewCellDelegate
@optional
- (void)textViewDidChange:(UITextView *)textView forIndexPath:(NSIndexPath *)indexPath;
- (void)textViewTableViewCellDoneTyping:(UITextView *)textView forIndexPath:(NSIndexPath *)indexPath;
- (BOOL)shouldChangeEditTextCellText:(TextViewTableViewCell *)cell newText:(NSString *)newText;
@end
@interface TextViewTableViewCell : UITableViewCell <UITextViewDelegate>

但是如果我使用我实现此协议的类中的任何函数,它就会崩溃

我不知道为什么会这样。据我说,可选方法不是强制性的。

当调用委托函数并且我们调用协议方法时,它会在此方法上崩溃

- (void)textViewDidChange:(UITextView *)textView
{
[self.delegate textViewDidChange:self.textView forIndexPath:self.indexPath];
}

@optional注释要求编译器避免生成生成生成警告,如果符合协议的类尚未添加实现。但是,这并不意味着您可以执行可选方法而不期望崩溃。

使用 respondsToSelector: 确认对象是否可以响应选择器。

if ([self.delegate respondsToSelector:@selector(textViewDidChange:forIndexPath:)])

不过,在 Swift 中,事情更简单。您可以在方法调用之前使用 "?":

delegate?.textViewDidChange?(textView: self.textView, forIndexPath: self.indexPath)
  • 如果您没有在其他类上实现委托方法,而是调用它,就会发生这种情况。要处理崩溃,请使用以下代码

- (void)textViewDidChange:(UITextView *)textView
{
    if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) {
            [self.delegate textViewDidChange:self.textView forIndexPath:self.indexPath];
    }
}

最新更新