What is the difference between Notifications, Delegates, and Protocols? - iphone

What is the difference between Protocols or Delegates and NSNotifications? What is an "Observer" and how does it work?

Protocols
Documentation: Protocols
Protocols are interfaces which define certain methods that objects respond to. The key thing about protocols is that they can be adopted by any class, guaranteeing that an object responds to those methods.
If you declare a protocol:
#protocol Photosynthesis
#required
- (void)makeFood:(id<Light>)lightSource;
#optional
+ (NSColor *)color; // usually green
#end
Then you can adopt it from other classes which are not necessarily directly related:
#interface Plant : Eukaryote <Photosynthesis>
// plant methods...
#end
#implementation Plant
// now we must implement -makeFood:, and we may implement +color
#end
or
#interface Cyanobacterium : Bacterium <Photosynthesis>
// cyanobacterium methods...
#end
#implementation Cyanobacterium
// now we must implement -makeFood:, and we may implement +color
#end
Now, elsewhere, we can use any of these classes interchangeably, if we only care about conformance to the protocol:
id<Photosynthesis> thing = getPhotoautotroph(); // can return any object, as long as it conforms to the Photosynthesis protocol
[thing makeFood:[[Planet currentPlanet] sun]]; // this is now legal
Delegates & Notifications
Documentation: Cocoa Design Patterns
These are two ways to pass messages between objects. The main difference:
with delegates, one designated object receives a message.
any number of objects can receive notifications when they are posted.
Delegates are usually implemented using protocols: a class will usually have something like
#property (weak) id<MyCustomDelegate> delegate;
which gives the delegate a certain set of methods to implement. You can use
myObject.delegate = /* some object conforming to MyCustomDelegate */;
and then the object can send relevant messages to its delegate. For a good common example, see the UITableViewDelegate protocol.
Notifications, on the other hand, are implemented using NSNotificationCenter. An object (or more than one object) simply adds itself as an observer for specific notifications, and then can receive them when they are posted by another object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(notificationHappened:)
name:MyCustomNotificationName
object:nil];
Then just implement
- (void)notificationHappened:(NSNotification *)notification {
// do work here
}
And you can post notifications from anywhere using
[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
object:self
userInfo:nil];
And make sure to call removeObserver: when you're done!

You can find answers by searching in stackoverflow ...
Delegates and notifications
Protocoles and delegates

Related

Do I want a #protocol declaration or something else to make sure sub-class defines selectors?

I have a class that does some generic code for Writing to a Database. Bring up the popovers, and controls, etc. Though there are many types of elements that I can write out to the database, each sub-class needs to have its own -(void) writeTagValue selector to implement the element's write.
The base-class has a selector that does the call to self.writeTagValue though since the base class does not really do any writing, its -(void) writeElement selector is empty with an abort(); in it.
I've implemented a protocol in the base class.h
#protocol IoUISEWriteAnimation <NSObject>
-(void) writeTagValue;
-(IBAction)saWriteValue:(NSNotification *)notification;
#end
added the protocol to the Sub-classes and now if the sub-classes don't define the selectors, I get compiler warnings.
What I want to know is, is there a way to remove the empty -(void) writeElement selector in the base class?
You can do something like this:
#protocol MyProtocol<NSObject>
#required
-(void) myRequiredMethod;
#optional
-(void) myOptionalMethod;
#end
And when you need to call an optional method, you do something like this:
if ([delegate respondsToSelector:#selector(myOptionalMethod)])
[delegate myOptionalMethod];
else
// abort, or ignore.
So long as the implementation class implement the required methods in the protocol, your base class does not need an empty implementation of that method. However, since it's required, the base class cannot specify that it implements the protocol.
You're on the right path.

What is the difference between Delegate and Notification?

What is the difference between Delegate and Notification?
I understood like delegate and protocol,
#protocol classADelegate
-(void)DelegateMethod;
#end
classB <classADelegate>{
classA *ObjOfclassA=[[classA alloc]init];
ObjOfclassA.delegate=self;
//while push later, here we have taken the pointer of classB(self) to `classA` and stored in delegate variable of classA. So, from `classA` we can call the function in `classB`
push:classA from here.
-(void)DelegateMethod{
nslog(#"i am rithik from India");
}
}
classA{
id <classADelegate> delegate;
-(void)viewdidload{
[self.delegate DelegateMethod];
}
}
My doubt is
1. Why don't we use in classA like this
classA{
**classB** <classADelegate> delegate;
[self.delegate DelegateMethod];
}
What is the reason for using "id" and what is the difference of them?
2. we have call the method of classB's DelegateMethod function which is came from protocol definition.
instead we can straightly call that method by defining that instance method of classB.because we have the got the pointer for classB in classA's delegate variable.
like this.
classB{
-(void)DelegateMethod;
}
and then call this in
classA{
classB delegate;
-(void)viewdidload{
[self.delegate DelegateMethod];
}
}
So, from the above we have avoided the protocol and id variable .
but I knew many of us use delegate and protocol. Here I came to know about any advantages while use delegate and protocol
here what is the usage of protocol implementation for method of DelegateMethod function.
instead instance definition .
What is the usage of those by #protocol. Please any one guide me right direction.
I'm new to iphone developement. Right now, I knew how to create delegate. but while I came to study about the NSNotification
That is also do the almost right job like delegate. So, when should I use the delgate or NSnotification.
Short Answer: You can think of delegates like a telephone call. You call up your buddy and specifically want to talk to them. You can say something, and they can respond. You can talk until you hang up the phone. Delegates, in much the same way, create a link between two objects, and you don't need to know what type the delegate will be, it simply has to implement the protocol. On the other hand, NSNotifications are like a radio station. They broadcast their message to whoever is willing to listen. The radio station can't receive feedback from it's listeners (unless it has a telephone, or delegate). The listeners can ignore the message, or they can do something with it. NSNotifications allow you to send a message to any objects, but you won't have a link between them to communicate back and forth. If you need this communication, you should probably implement a delegate. Otherwise, NSNotifications are simpler and easier to use, but may get you into trouble.
Long Answer:
Delegates are usually a more appropriate way of handling things, especially if you're creating a framework for others to use. You gain compile time checking for required methods when you use protocols with your delegates, so you know when you compile if you're missing any required methods. With NSNotificationCenter you have no such guarantee.
NSNotificationCenter is kind of "hack-ish" and is frequently used novice programmers which can lead to poor architecture. A lot of times these two features are interchangeable, but more "hardcore" developers might scoff at the use of the NSNotificationCenter.
Q: what is the reason for using "id" and what is the difference of them?
A: Using id allows you to send any object to the method as a parameter. Note that you can not send primitives such as bools, floats, doubles, ints, etc. unless they are wrapped in their respective Object wrappers.
classB{
-(void)DelegateMethod;
}
and then call this in
classA{
classB delegate;
-(void)viewdidload{
[self.delegate DelegateMethod];
}
}
The above example you provided would require that classA's delegate always be of type classB, which isn't advantageous. Instead of using delegates in this scenario, you would probably just use a variable that referred to your other class, say, myClassB. The beauty of delegates is that you can pass around any object, and the code just works as long as they implement the required methods (which the compiler ensures, as long as it's marked as the correct delegate type).
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<ClassADelegate> delegate;
}
// Make sure you are using assign, not retain or copy
#property (nonatomic, assign) id<ClassADelegate> 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 <ClassADelegate>
{
}
- (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
Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols.
Simply We can say,
Delegates:
One - to - One
Notification:
One - to - Many
To declare Delegate
#protocol DelegateName
#required
- (void)method:(NSString *)param;
#optional
- (void)methodOptional:(NSString *)param;
#end
And declare a property for Protocol
#property id <DelegateName> delegate;
You can use
myObject.delegate = <# some object conforming to DelegateName #>;
NSNotification declaration
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(notificationHappened:)
name:MyCustomNotificationName
object:nil];
Then Implement
- (void)notificationHappened:(NSNotification *)notification {
// do work here
}
You can post Notification from anywhere using,
[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
object:self
userInfo:nil];
call removeObserver: when you are finished.
We can use notifications for a variety of reasons. For example, you could broadcast a notification to change how user-interface elements display information based on a certain event elsewhere in the program. Or you could use notifications as a way to ensure that objects in a document save their state before the document window is closed.
The general purpose of notifications is to inform other objects of program events so they can respond appropriately.But objects receiving notifications can react only after the event has occurred. This is a significant difference from delegation.
The delegate is given a chance to reject or modify the operation proposed by the delegating object. Observing objects, on the other hand, cannot directly affect an impending operation.

NSNotification addObserver:someOtherClass

I need to pass a message up to a controlling class (which creates an instance of the class which will be sending the message) So, I cannot directly reference the class name in my file, without either making it a Global (which is ridiculous to do if "NSNotification" advertises to be able to pass all kinds of messages, regardless of where / what class they are.
So without further ado...
(calling from Say ClassB)
ClassA creates instance of ClassB
Now in ClassB, I need to pass messages regarding button presses back up to ClassA
(insdie ClassB)
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:ClassA
selector:#selector(doLoginAction)
name:#"SomeButton"
object:nil];
[super viewDidLoad];
}
This will NOT compile, even when I include, sorry, "#import "ClassA.h"
Now if I do something stupid like,
ClassA *classa = [[ClassA alloc]init];
and then use this Newly created instance of classa in addObserver:classa it will compile, but as I thought, will do absolutely nothing... (I knew that, but surprisingly this kind of code is prevalent in Iphone programming books...) So I tried it anyway.
But if I put this function in ClassA and use addObserver:ClassB
it will get called, but will cause a stack dump unrecognized selector sent to instance
or use addObserver:self.
I am tempted to delete Xcode and go back to vim and use a good old "C" callback...
So, if I get it right, you have a ClassA which creates instances of ClassB. Those instances, in turn, should send notifications directly to ClassA without knowing anything about it.
If that is correct, then NSNotificationCenter is exactly what you need.
In ClassA implementation add an initialialize method like this:
#implementation ClassA
+ (void)initialize
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(YourSelector:)
name:#"YourNotificationName"
object:nil];
}
+ (void)YourSelector:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
// ...
}
// ...
#end
Then, instances of ClassB should post their notifications using only its name:
#implementation ClassB
- (void)postNotification
{
NSDictionary *userInfo = ...; // may be nil
[[NSNotificationCenter defaultCenter]
postNotificationName:#"YourNotificationName"
// the same name is used in the `addObserver` call
// in the previous code snippet
object:nil
userInfo:userInfo];
}
// ...
#end
To sum it all up, you do not need to know anything about the receiver of notifications if you are using NSNotificationCenter. In fact, you may subscribe as many objects as you like to receive the same notification, and each of them will call its appropriate method (specified in addObserver) upon receiving the notification object.
Please remember that in the case when you add a class instance as an observer, rather than the class object itself, you should call [[NSNotificationCenter defaultCenter] removeObserver:self] in that instance's dealloc method.
I see a couple of problems here.
First you need to stop trying to use classes and instances interchangeably. Until you have a reasonable mental model of what your classes and instances represent and what they are responsible for you're going to have all sorts of confusion around when to use which one and OOP in general.
NSNotificationCenter allows you to register a specific instance of a class, a single object, as an observer of particular notifications. You need to be aware of, and have a reference to, the observing object in order to register it as an observer.
Secondly you need to consider what each of your classes, and therefor their instantiated objects are responsible for. What they should know, what they do not need to know, and how they can communicate.
Let's assume you create ObjectA as an instance of ClassA and it creates ObjectB which is an instance of ClassB. Now ObjectA is aware of ObjectB, after all A just created B so it is easy for A to have a reference to B. ObjectB is not yet aware of ObjectA; B was created but it need not know by which object or even what class that object was an instance of. If you want ObjectB to be able to communicate with ObjectA you have a couple of options.
Delegation: ObjectA sets a property on ObjectB to point back to ObjectA, now B can send messages to A directly. Now your two objects are coupled together which can be both useful and problematic.
Notifications: ObjectB can post notifications, ObjectA can observe notifications. B does not need to know that A is observing those notifications and A does not need to know that the notifications originated with B (though it could). These objects are very loosely coupled and you could change many things about your application without them ever being aware of it.
Importantly, if ObjectA is to listen for notifications then it is A's responsibility to add itself as an observer. Since B is not aware of A there's no way B can make A an observer. A's creator could since that object would have a reference to A but A's children cannot unless they were given some reference to A.
Looks like Alex chimed in with an excellent answer so hopefully this will all be useful.

Compiler gives warning on performSelectorOnMainThread:#selector(delegateMethod)

I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.
As the NSOperation lives on a different thread I have to make the call like this:
[delegate performSelectorOnMainThread:#selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
It works just fine, but it gives me a warning:
warning:
'-performSelectorOnMainThread:withObject:waitUntilDone:'
not found in protocol(s)
I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.
My question is: can I remove the warning by making this call in a different manner?
My two guesses are that I could (1) write a method called
- (void) callDelegateMethodOnMainThred {
[delegate getDealersIDSuccess:result]
}
and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.
The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.
I would really appreciate a third solution from someone with a better understanding of the language:)
Thank you in advance.
EDIT: Added delegate declaration:
id <ISDealersIDDelegate> delegate;
I declare my delegate as id. The delegate it self extends UIViewController.
I could see that declaring it NSObject would work.
performSelectorOnMainThread:withObject:waitUntilDone: method is declared in NSObject class. If your delegate object inherits from NSObject you can declare it as
NSObject<MyDelegateProtocol> *delegate;
So compiler will know that delegate responds to NSObject's methods and won't issue a warning.
It might be even a better solution not call performSelectorOnMainThread: on a delegate or other protocol implementation.
Make it the responsibility of the delegate/receiver to determine if it needs to do things on the main thread.
[delegate performSelector:#selector(delegateAction:)
withObject:actionData];
Delegate implementation
- (void)delegateAction:(NSData*)actionData
{
[self performSelectorOnMainThread:#selector(updateUIForAction:)
withObject:actionData
waitUntilDone:NO];
}
- (void)updateUIForAction:(NSData*)actionData
{
// Update your UI objects here
}
It might look like more code, but the responsibility is in the right place now
Actually on iOS 4 I prefer using NSNotifications and Observers (with Blocks) to perform updates on the mainthread.
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block
I wrote down my design here.
1) Declare your delegate's protocol to extend the NSObject protocol in the .h file
#protocol YourDelegateProtocol <NSObject>
2) Cast to NSObject in your call
[(NSObject*)delegate performSelectorOnMainThread:#selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
I definitely recommend number (1).

Creating an object to act as a delegate - Objective C

My question is simple actually, how do I create an object to act as a delegate, instead of including the delegate methods in my view?
For example, I have x functionality that requires delegate methods, and they're currently setup to use self as the delegate. I'd like to put those methods in their own object so that the delegate methods can be called and do stuff if the view has ended.
What's the best way?
for example, NSXMLParser delegate methods - they exist, the delegate is defined, but I dont want to call them as self in my view controller... what other option do I have?
You can specify another custom class to handle the delegate methods, if you wish. Simply create a class, call it MyXMLParserDelegate or something similar. Then, all you have to do is tell your NSXMLParser object that it should use an instance of your class as its delegate.
If you are using Interface Builder, add a new object to the XIB file, set its class to MyXMLParserDelegate, and then drag a connection from your NSXMLParser object's delegate selector to the new object.
If you are doing it programmatically, the basic operation looks like this:
MyXMLParserDelegate * myDelegate = [[MyXMLParserDelegate alloc] init];
[someXMLParser setDelegate:myDelegate];
Keep in mind, however, that delegates are not retained, so in order to do this without leaking memory, you should add an ivar of type MyXMLParserDelegate to your viewController class, and then do the following:
// in your #interface block:
{
...
MyXMLParserDelegate * myDelegate;
}
// in your init method:
myDelegate = [[MyXMLParserDelegate alloc] init];
// in your awakeFromNib method (or anywhere else it seems appropriate):
[someXMLParser setDelegate:myDelegate];
// in your dealloc method:
[myDelegate release];
Check out this answer, I think it covers what you need: How to use custom delegates in Objective-C