[英]How can be 'Class is implemented in both' issue be solved inside of an iOS framework?
[英]How I can determine if a method is implemented in a class in iOS
我有兩個班級(例如BusyMan 和NotBusyMan),BusyMan 想看電影,但他沒有時間買票,NotBusyMan 可以幫助他。 BusyMan 有一個名為委托的屬性
@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
。
// *** Check method is implemented or not ***
if([self.delegate respondsToSelector:@selector(buyTicketForMe)]) {
// *** Invoke method ***
[self.delegate performSelector:@selector(buyTicketForMe) withObject:nil];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.