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

Ios 协议可选方法在未实现时提供崩溃,ios,objective-c,protocols,Ios,Objective C,Protocols,我正在使用一些可选方法的协议 #import <UIKit/UIKit.h> @class TextViewTableViewCell; @protocol TextViewTableViewCellDelegate @optional - (void)textViewDidChange:(UITextView *)textView forIndexPath:(NSIndexPath *)indexPath; - (void)textViewTableViewCellDoneTy

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

#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>

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

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

if ([self.delegate respondsToSelector:@selector(textViewDidChange:forIndexPath:)])
然而,在斯威夫特,事情更简单。您可以在方法调用之前使用“?”:

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


谢谢@Puneet Sharma,我不知道这一点,“但是,这并不意味着你可以调用可选方法,如果它没有实现,你就不会期望崩溃。”谢谢你的回答,我会记住它。我非常确定OP需要检查选择器中的textViewDidChange:forIndexPath:。如果OP要在选择器中检查textViewDidChange:,它实际上是在检查错误的方法@Parv Bhasker:FYI
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];
    }
}