I’m trying to set up protocols and delegation.
I have a problem tho that i wish to set a delegate to a previously allocated object.
The object i am allocating needs to delegate to a protocol. how is this done?
Heres my code.
//SendSMS.h
@protocol ModalViewDelegate
- (void)didReceiveMessage:(NSString *)message;
@end
@interface SendSMS : UIViewController <UITextViewDelegate, UITextFieldDelegate> {
MessageOptions *messageOptions;
LoginPage *loginPage;
IBOutlet UITextField *phonenumber;
IBOutlet UITextView *smsBody;
IBOutlet UIScrollView *scrollview;
}
-(IBAction)LoadMessageOptions;
@end
The problem is when the object is pushed onto the stack. Its delegate isn’t that of its self. but that of the object before it.
Any ideas?
UPDATE!
Ok i have managed to set my delegate to [self.navigationController.viewControllers objectAtIndex:0] which is the rootviewcontroller. But i have 3 complier warnings stating that the methods are not found in the protocols. Which they are…. But it compiles runs and works.
Never let an instance set the delegate unto itself. The whole idea with delegates is that you should not need to know who the delegate is. As I understand your architecture it is three levels deep;
View1is the root controller, it creates and pushes;View2that do some stuff and then creates and pushes;View3that wants to send some results to whoever is concerned.I see two possible solutions.
Solution 1 – Delegates
View3declare a delegate protocolView3Delegate.View1conform toView3Delegate.View1creates and pushesView2also pass itselfto hold on to.View2creates and pushesView3also set the delegate that was passed in step 3.View3wants to send it’s result, call the delegate and be happy.Solution 2 – Notifications
This is probably a more elegant solution in your case, since the previous solution has an extra step where
View2needs to handle stuff just in order to makeView1andView3work, not related to it’s real responsibilities.View3declare a notification namedView3ResponseNotification.View1observe notifications of the nameView3ResponseNotification.View1creates and pushesView2with no worries.View2creates and pushesView3with no worries.View3wants to send it’s results it posts theView3ResponseNotificationnotification.