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).
Related
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?
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.
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 have this inside a class
[delegate performSelector:#selector(doStuff:) withObject:myObject afterDelay:2.0];
and I am having this error
warning:
'-performSelector:withObject:afterDelay:'
not found in protocol(s)
I cannot figure out what may be wrong.
any clues?
thanks.
Your problem is that you've declared your delegate instance variable as:
id<SomeProtocol> delegate;
Right? Well, that means that the compile-time checker is only going to look for methods in the <SomeProtocol> protocol. However, performSelector:withObject:afterDelay: is declared on NSObject. This means that you should declare the ivar as:
NSObject<SomeProtocol> * delegate;
This is saying that it must be an NSObject that conforms to <SomeProtocol>, as opposed to any object that conforms to <SomeProtocol>. This should get rid of your warning, and you don't have to do any casting.
Try casting the delegate to its class' type first, then invoke performSelector:withObject:afterDelay:
[(SomeClass *) delegate performSelector:#selector(doStuff:) withObject:myObject afterDelay:2.0];
Assuming that your delegate is of type id, you need to tell the runtime that the object in fact does inherit from NSObject (where the performSelector:withObject:afterDelay: method is defined) by casting it to it's class' type.
Although the NSObject * cast Dave brought up will work, there's a cleaner alternate way that lets people use protocols as they would expect - you can have the protocol itself declare it supports the NSObject protocol.
NSObject is not just an implementation but also a protocol that includes all of the performSelector: method variants. So you can simply declare in your protocol that you support NSObject like you would any other class supporting a protocol:
#protocol MyProtocol <NSObject>
And the compiler warnings will vanish (assuming you have imported the protocol definition).
Note that this does mean going forward anyone that declares support of your protocol would pretty much have to be an NSObject or inherit a lot of methods. But all classes used in iPhone programming are derived from NSObject due to practical considerations, so that's generally not an issue.
EDIT:
It turns out the -performSelector:withObject:afterDelay: is not in the NSObject protocol (the ones without the delay are). Because it's still nicer to everyone using your protocol if they can just use id to reference a protocol type, I'd still use a protocol to solve this - but you'd have to declare an extension to the NSObject protocol yourself. So in the header for your file you could add something like:
#protocol MyProtocolNSObjectExtras <NSObject>
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
#end
#protocol MyProtocol <NSObjectExtras>
....
#end
Then you get all the same benefits as I described previously.
You need to cast the delegate object to the actual class you are working in order to have the methods. Seen the delegate only can only show the methods defined in the protocol. performSelector:withObject: is not a method defined in the protocol.
[(CLASS*)delegate performSelector:#selector(doStuff:) withObject:myObject afterDelay:2.0];
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:#selector(doStuff)
userInfo:nil
repeats:NO];
Try that assuming you just want a timer
This could be me doing the design pattern wrong.
I'm implementing asynchronous delegation in an application that uses NSURLConnection. An object wraps the NSURLConnection and handles its delegated messages; that works fine. Now I'm defining my own delegates in the object that uses it (NSURLConnection messages ConnectionWrapper, ConnectionWrapper messages NeedsToUseConnection, you get the idea), and that works as well, however, Xcode emits this warning:
No '-request:finishedWithResult' method found
This is, presumably, because I'm declaring the delegate I'm calling like this:
id<NSObject> delegate;
...and Xcode is checking what NSObject declares in the Foundation framework. My custom delegate message is not there. I am properly insulating the call:
if([delegate respondsToSelector:#selector(request:finishedWithResult:)])
[delegate request:self finishedWithResult:ret];
Aside from turning the warning off -- I like to work with as many warnings on as possible -- is there a way to communicate (either syntactically or via a compiler directive) that I am aware this message is undeclared? Should I, instead, be using an interface design pattern for this á la Java? Using id<WillReceiveRequestMessages> or something?
Open to suggestion.
A better way of doing it would be to create your own delegate protocol:
#protocol MyControlDelegate <NSObject>
#optional
- (void)request:(MyControl *)request didFinishWithResult:(id)result;
#end
Then, you would declare your delegate like this:
id <MyControlDelegate> delegate;
The compiler will no longer complain when you write this:
if ([delegate respondsToSelector:#selector(request:didFinishWithResult:)])
[delegate request:self didFinishWithResult:result];
The <NSObject> syntax is important in the protocol definition because it tells the compiler to incorporate the NSObject protocol. This is how your protocol gets methods like respondsToSelector:. If you left that out, the compiler would start complaining about respondsToSelector: instead.
This is, presumably, because I'm declaring the delegate I'm calling
like this: ...and Xcode is checking what NSObject declares in the
Foundation framework.
That is incorrect. If that were the case then you would get a warning about the object "may not respond to" the method, or something like that. This is a completely separate problem.
This warning is due to the fact that the compiler must know the signature of a selector in order to call it. This is because, behind the scenes, the compiler translates a method call to either objc_msgSend or objc_msgSend_stret depending on whether the method returns a struct type or not. If it doesn't know the return type, it will guess that it is not a struct, and use the first function. However, this could be wrong.
The solution is to have the method declared anywhere at all. It doesn't even have to be declared in the right class. You can declare it in some dummy protocol that is never used. So long as it is declared somewhere, the compiler will know and will be able to correctly compile it.