0

I want to clarify the concept of delegate and protocols in objective c. So there are two types of protocols 1)Formal 2)Informal

In case of formal delegate.. what if the person has defined the protocol method but not ACTUALLY implemented it in both . i.e Class B is delegate of A and A has method WindowDidMove as optional...in that case. what would the behavior be??? and is it must to implement the delegate function in Class b. can't i just implement it in A and use it everywhere i want... and Conversely not define it in A, and give separate implementations in B or class C or D and use them however i want... please clarify this point – @class A;

@protocol ADelegate <NSObject>
@optional

- (BOOL)A:(A *)foo doSumfin:(BOOL)decide;

@end

@interface A : NSObject {
NSString *bar;
id <ADelegate> delegate;
}

@property (nonatomic, retain) NSString *bar;

@property (nonatomic, assign) id <ADelegate> delegate;

- (void)someAction;

@end

Also, what does the line

id  <A Delegate > delegate; 

@property (nonatomic, assign) id <ADelegate> delegate;

help us achieve..

in case of informal protocol... if i don't give an implementation for a method and still call the delegate method... what would happen.?

Izac Mac
  • 491
  • 3
  • 20

1 Answers1

2

If you call a delegate method that your delegate doesn't implement, this will result in an exception. For optional delegate methods, you will usually check if the delegate implements them by checking first if the delegate responds to it:

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

This doesn't change in any way with an informal protocol. Don't confuse informal protocols with optional protocol methods. An informal protocol is usually just an NSObject category and shouldn't really be used anymore.

omz
  • 53,243
  • 5
  • 129
  • 141
  • please edit the answer to explain the scenario 2 as well...in case of formal protocol.. what if i give separate implementations for a single optional method in different classes also what will happen if i give the implementation in in the protocol class and want to use that everywhere else. please clear this point as well – Izac Mac May 08 '12 at 08:42