简体   繁体   English

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

[英]protocol optional methods giving crash when not implement

I am using protocol with some optional methods used 我正在使用协议,使用一些可选方法

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

But it is giving crash if I'am using any of the function in the class i implemented this protocol 但是如果我使用我实现此协议的类中的任何函数,它就会崩溃

I don't know why this is happening. 我不知道为什么会这样。 According to me optional method is not compulsory to use. 根据我的可选方法不是强制使用。

it giving crash on this method when the delegate function is called and we call the protocol method 当调用委托函数并调用协议方法时,它会给这个方法带来崩溃

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

@optional annotation asks compiler to avoid generating build warnings, if the class which conforms the protocol has not added the implementation. @optional注释要求编译器避免生成构建警告,如果符合协议的类尚未添加实现。 But, it does not mean that you can execute optional method and not expect a crash. 但是,这并不意味着您可以执行可选方法而不会发生崩溃。

Use respondsToSelector: to confirm whether the object can respond to the selector or not. 使用respondsToSelector:确认对象是否可以响应选择器。

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

In Swift, though, things are simpler. 但是在Swift中,事情变得更简单了。 You can use "?" 您可以使用 ”?” before method call: 在方法调用之前:

delegate?.textViewDidChange?(textView: self.textView, forIndexPath: self.indexPath)
  • Its happen if you didn't implement the delegate method on other class but you calling it. 如果您没有在其他类上实现委托方法但是调用它,则会发生这种情况。 To handle crash please use below code 要处理崩溃,请使用以下代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM