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

Par*_*ker 1 protocols objective-c ios

我正在使用带有一些可选方法的协议

#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>
Run Code Online (Sandbox Code Playgroud)

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

我不知道为什么会发生这种情况。据我所知,可选方法并不是强制使用的。

当调用委托函数并且我们调用协议方法时,它会导致该方法崩溃

- (void)textViewDidChange:(UITextView *)textView
{
[self.delegate textViewDidChange:self.textView forIndexPath:self.indexPath];
}
Run Code Online (Sandbox Code Playgroud)

Pun*_*rma 5

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

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

if ([self.delegate respondsToSelector:@selector(textViewDidChange:forIndexPath:)])
Run Code Online (Sandbox Code Playgroud)

但在 Swift 中,事情就更简单了。您可以使用 ”?” 方法调用之前:

delegate?.textViewDidChange?(textView: self.textView, forIndexPath: self.indexPath)
Run Code Online (Sandbox Code Playgroud)