除了@micantox提供的答案之外,我还要补充一点,struct
您可以使用它NS_OPTIONS
来定义一个bitmask
.
typedef NS_OPTIONS (NSUInteger, MyDelegateOptions)
{
MyDelegateOptionDidFinishedWithTaskOne = 1 << 0,
MyDelegateOptionDidFinishedWithTaskTwo = 1 << 1,
MyDelegateOptionDidFinishedWithTaskThree = 1 << 2
};
然后,您可以创建可以保存的属性bitmask
:
@property (nonatomic, assign) MyDelegateOptions delegateOptions;
并检查respondsToSelector:
您的设置器中的委托是否像
- (void)setDelegate:(id<MyDelegateProtocol>)delegate
{
_delegate = delegate;
if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskOne:)]) {
{
self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskOne;
}
if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskTwo:)]) {
{
self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskTwo;
}
if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskThree:)]) {
{
self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskThree;
}
}
然后您可以使用简单地检查分配的位模式bitwise AND
if (self.delegateOptions & MyDelegateOptionDidFinishedWithTaskOne) {
[self.delegate myDelegateDidFinishedWithTaskTwo:myResult];
}
如您所见,即使设置了其他位,如果将位设置为1bitwise AND
,使用将返回。true
MyDelegateOptionDidFinishedWithTaskOne
因此,如果您假设delegate
已在您的设置器中检查并基于此您的delegateOptions
持有位模式00000111和您MyDelegateOptionDidFinishedWithTaskOne
表示的位模式00000001然后只需使用bitwise AND
00000111 & 00000001 = 00000001
你会得到true
你的条件语句。
值得注意的是,在您delegate
只需要检查一次或两次的情况下,这太过分了。