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.
Related
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
Are there alternatives to "delegates" to pass back data from one controller to another?
Just seems like a lot of work implementing a delegate just to pass back the result from a child controller, back to the parent controller. Is there not another method? Are "blocks" one answer, and if so some example code would be great.
Delegates aren't a lot of work, aren't a lot of code, and are commonly the most appropriate solution. In my opinion they're neither difficult nor messy.
Five lines of code in the child's interface. Before #interface:
#protocol MyUsefulDelegate <NSObject>
- (void)infoReturned:(id)objectReturned;
#end
Inside #interface:
id <MyUsefulDelegate> muDelegate;
After #inteface's #end:
#property (assign) id <MyUsefulDelegate> muDelegate;
One line of code in the child's implementation:
[[self muDelegate] infoReturned:yourReturnObject];
One addition to an existing line of code in the parent's interface:
#interface YourParentViewController : UIViewController <MyUsefulDelegate>
Three lines of code in the parent's implementation. Somewhere before you call the child:
[childVC setMuDelegate:self];
Anywhere in the implementation:
- (void)infoReturned:(id)objectReturned {
// Do something with the returned value here
}
A total of nine lines of code, one of which is merely an addition to an existing line of code and one of which is a closing curly brace.
It's not as simple as a returning a value from a local method, say, but once you're used to the pattern it's super straightforward, and it has the power of allowing you do do all kinds of more complex stuff.
You could use many ways:
Calling a method of the super controller, needs casting maybe
Notifications
Simple Key-Value-Observing
Core Data
Example for for 1.
interface of your MainViewController: add a public method for the data to be passed
- (void)newDataArrivedWithString:(NSString *)aString;
MainViewController showing ChildController
- (void)showChildController
{
ChildController *childController = [[ChildController alloc] init];
childController.mainViewController = self;
[self presentModalViewController:childController animated:YES];
[childController release];
}
Child Controller header / interface: add a property for the mainViewController
#class MainViewController;
#interface ChildController : UIViewController {
MainViewController *mainViewController;
}
#property (nonatomic, retain) MainViewController *mainViewController;
Child Controller passing data to the MainViewController
- (void)passDataToMainViewController
{
NSString * someDataToPass = #"foo!";
[self.mainViewController newDataArrivedWithString:someDataToPass];
}
KVO or notifications are the way to go in many cases, but delegation gives a very good foundation to build upon. If you plan on extending the relationship between the view controllers in the future, consider using delegation.
Blocks are not really relevant to the above, but in short - it is a technique introduced with iOS 4, where you pass around blocks of code as variables/ parameters. It is very powerful and has many uses. For example, here is how you enumerate objects in an array using a block:
[someArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
NSLog(#"obj descriptions is - %#", [obj description]);
}];
The part from the ^ until the } is a block. Note that I've passed it in as parameter. Now, this block of code will be executed for every object in the array (i.e. output will be the description of each object).
Blocks are also very efficient performance-wise, and are used heavily in many new frameworks.
Apple's blocks beginners guide is quite good.
Check out NSNotificationCenter — NSNotificationCenter Class Reference
Folks pay a lot of attention the the V and the C in MVC, but often forget the M. If you've got a data model, you can pass it from one controller to the next. When one controller makes changes to the data stored in the model, all the other controllers that share the same model will automatically get the changes.
You might find using a singleton is practical. Just use it as a central storage for all your shared data.
Then throw in saving the state of your application too;)
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.
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).
When using property/synthesize for a UITableView, UIButton, etc should self be included in the method call on that variable? Using UITableView as an example is there a difference between [self.myTableView visibleCells] and [myTableView visibleCells]? Or say [self.myImage setImage:...] and [myImage setImage:...]?
I've seen Apple code that does use self (Bubble Level) and examples in the book Beginning iPhone Development that do not use self. I'd like to understand this better, especially since using self in my UIScrollView method calls has caused erratic/buggy scrolling behavior. Thanks.
Using self.myTableView is another way of saying [self myTableView] (it can also be [self setMyTableView:...]; if used in an assignation statement). In other words, you're executing a method.
Using myTableView accesses the instance variable directly.
Personally, I generally prefer using the former method, since it usually frees me from manually managing memory and gives me the benefit of KVO notifications. However, there is the miniscule overhead of the extra method call, which you may wish to avoid.
Which style you choose to use is up to you, and each way has its benefits and disadvantages.
The difference comes down to how you define the property. For example, say you have the following:
#interface MyObject : NSObject {
NSObject *memberVariable;
}
#property (nonatomic, retain) NSObject *memberVariable;
#end
#implementation MyObject
#synthesize memberVariable;
#end
Specifying (nonatomic, retain) actually tells #synthesize how to create the getter and setter methods. Specifying retain causes the setter method to call retain on objects I pass to it. So, self.memberVariable = someOtherObject is equivalent to memberVariable = [someOtherObject retain];
This is also why you should never do self.memberVariable = [[NSObject alloc] init]; if you've specified retain in the property definition. alloc initializes the retain count to 1, passing the object to the setter method increases the retain count to 2.
This comes down to whether or not your accessor methods have custom behavior, in which case you'd always want the accessors called even from within the class, and whether you want to make sure KVO notifications are generated. If you're using stock accessors (e.g., synthesized) and it won't affect anything to access the instance variable directly from within the class, you're saving yourself a method call.