views:

243

answers:

2
- (void)someMethod {
    if ( [delegate respondsToSelector:@selector(operationShouldProceed)] ) {
        if ( [delegate operationShouldProceed] ) {
            // do something appropriate
        }
    }
}

http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW29 The documentation says.

The precaution is necessary only for optional methods in a formal protocol or methods of an informal protocol

What does it mean? if I use a formal protocol I can just use [delegate myMethod]?

+2  A: 

You use it pretty much just when you think you need to: to check to see if an object implements the method you are about to call. Usually this is done when you have an optional methods or an informal protocol.

I've only ever used respondsToSelector when I'm writing code that must communicate with a delegate object.

if ([self.delegate respondsToSelector:@selector(engineDidStartRunning:)]) {
        [self.delegate engineDidStartRunning:self];
    }

You sometimes would want to use respondsToSelector on any method that returns and id or generic NSObject where you aren't sure what the class of the returned object is.

kubi
thanks. I understand now. I noticed you use self.delegate, which is a property. I just use an instance variable: id delegate. what's the difference? Im learning objective-c. thanks again
Taho
`self.delegate` is exactly the same as calling `[self delegate]`. In my code there's no difference between `[self.delegate someMethod]` and `[_delegate someMethod]`, but I tend to use dot syntax because it keeps it straight in my mind which variables are local to the method I'm in and which are instance variables.
kubi
If you're just starting, it will be worth your time to read Apple's guide to Obj-C. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17
kubi
one more question: do i need to set delegate = nil in the dealloc and viewDidUnload method?(of the delegate class or the class that implements the delegate or neither?)
Taho
No. Delegate properties should almost always be assigned instead of retained. In the vast majority of examples, you don't own the delegate object, so you shouldn't retain or release it. http://stackoverflow.com/questions/918698/why-are-objective-c-delegates-usually-given-the-property-assign-instead-of-retain/918732#918732
kubi
+2  A: 

Just to add to what @kubi said, another time I use it is when a method was added to a pre-existing class in a newer version of the frameworks, but I still need to be backwards-compatible. For example:

if ([myObject respondsToSelector:@selector(doAwesomeNewThing)]) {
  [myObject doAwesomeNewThing];
} else {
  [self doOldWorkaroundHackWithObject:myObject];
}
Dave DeLong
Nice catch. I forgot about that.
kubi