【问题标题】:How I can determine if a method is implemented in a class in iOS如何确定方法是否在 iOS 的类中实现
【发布时间】:2016-03-29 22:27:21
【问题描述】:

我有两个班(例如 BusyMan 和 NotBusyMan),BusyMan 想看电影,但他没有时间去买票,NotBusyMan 可以帮助他。 BusyMan 有一个名为 delegate 的属性

@property(nonatomic) id<BusyManDelegate> delegate;

NotBusyMan 是 BusyMan 的代表

busyMan.delegate = notBusyMan;

还有

@interface NotBusyMan : NSObject <BusyManDelegate>

假设在 BusyManDelegate 协议中声明了一个方法

@protocol BusyManDelegate<NSObject>

@optional
- (BOOL)buyTicketForMe;
@end

当 NotBusyMan 为 BusyMan 买票时,它返回 YES。 所以 BusyMan 可以这样问 NotBusyMan

BOOL result = [self.delegate buyTicketForMe];
if (result) {//I may watch the film now

}else{//Oh No

}

但 buyTicketForMe 是可选的,如果 NotBusyMan 没有实现该方法怎么办?我们都知道结果:一个异常,“无法识别的选择器发送到实例......”,可能会引发。 所以,我想在委托调用方法之前添加条件,

if (my delegate implemented the method,and it won't raise an excetion) {
   BOOL result = [self.delegate buyTicketForMe];
    if (result) {//I may watch the film now

    }else{//Oh No

    }
}

条件部分怎么写。

顺便说一句,responseToSelector: 不会有帮助,一旦接收者声明了 SEL,它就会返回 YES,实现的东西将被忽略。

【问题讨论】:

  • respondsToSelector: 不检查声明。它检查实施。如果它对您不起作用,则说明您在某处有错误。
  • 这就是为什么您应该在向 SO 发布问题之前尝试代码。

标签: ios objective-c delegates protocols


【解决方案1】:

使用以下方法检查respondsToSelector与特定对象。

// *** Check method is implemented or not ***
if([self.delegate respondsToSelector:@selector(buyTicketForMe)]) {
    // *** Invoke method ***
    [self.delegate  performSelector:@selector(buyTicketForMe) withObject:nil];
}

【讨论】:

  • @daredevil 更复杂,隐藏正在发生的事情。绝对是更糟糕的代码。
猜你喜欢
  • 2021-11-10
  • 2010-11-09
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2013-09-19
  • 2023-03-29
相关资源
最近更新 更多