What is the difference between Delegate and Notification?
I understood like delegate and protocol,
@protocol classADelegate
-(void)DelegateMethod;
A delegate uses protocols and creates a has-a relationship between the two classes. One of the other benefits of delegates is that you can return something back to the owning class.
Notifications, on the other hand, are more geared towards point to multipoint communication. An example of using an NSNotification might be in a tab bar controller application, where you may need to notify multiple view controllers of a particular event so they can refresh data, etc. This is great for classes that have no knowledge of one another and it wouldn't make sense if they did.
Now, to your other questions:
Why do we use id?
In your class, you want a handle to an object of indeterminate type, but which implements the protocol you define. Take UIWebView, for example. There can be infinitesimal types of classes that can be a delegate for it, therefore, it should not name a specific type of class, but specify that the class must implement the UIWebViewDelegate protocol. This reduces coupling to an absolute minimum and creates a highly cohesive application where you are creating interaction based on behavior, not state.
So, let's run through an example:
@protocol ClassADelegate
- (NSString*) determineValue;
@end
@interface ClassA : NSObject
{
id delegate;
}
// Make sure you are using assign, not retain or copy
@property (nonatomic, assign) id delegate;
@end
The implementation of ClassA:
import "ClassA.h"
@implementation ClassA
@synthesize delegate;
- (void) somePrivateMethod
{
if (self.delegate && [self.delegate implementsProtocol:@protocol(ClassADelegate)])
{
NSString* value = [self.delegate determineValue];
// Do other work
}
}
- (void) dealloc
{
delegate = nil;
}
@end
In the header, we declare that the class will implement the ClassADelegate protocol:
#import "ClassA.h"
@interface ClassB : NSObject
{
}
- (void) someMethod;
@end
In the implementation of ClassB we create an instance of ClassA and set B as the delegate of A:
#import "ClassB.h"
@implementation ClassB
- (void) someMethod
{
ClassA* aClass = [[ClassA alloc] init];
aClass.delegate = self;
// Other work and memory clean up of A.
// Some logic occurs in A where it calls the delegate (self) which will
// call the `determineValue` method of this class.
}
// Here's the delegate method we implement
- (NSString*) determineValue
{
return @"I did some work!";
}
@end