Defining a protocol to use one method only if another is running

I have a rather complicated protocol to which I add methods. Most new @optional methods, but they are conjugate.

For example, these two methods work together:

 @optional - (BOOL) shouldIDoSomethingHere; - (CGPoint) whereShouldIDoIt; 

In this example, if the first method is implemented, I want to declare the second method as @required , otherwise both are optional. What I want is a way to nest or group protocol methods as all necessary or not based on context.

Ideally, something like:

 @optional @required - (BOOL) shouldIDoSomethingHere; - (CGPoint) whereShouldIDoIt; @endRequired //... next optional method 
+4
source share
1 answer

During compilation, there is no way to enforce this. Best of all, at runtime, when your delegate property is set (or what you use to refer to an object that implements the protocol), just go ahead and implement all the matching rules that you need using -respondsToSelector: and throw an exception immediately if the object is not matches your rules. Sort of:

 - (void)setDeleate:(id<MyDelegate>)delegate { if ([delegate respondsToSelector:@selector(shouldIDoSomethingHere)]) { NSAssert([delegate respondsToSelector:@selector(whereShouldIDoIt)], @"Delegate must respond to -whereShouldIDoIt if it responds to -shouldIDoSomethingHere"); } // ... _delegate = delegate; } 
+2
source

All Articles