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;
LoginPag开发者_运维问答e *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;
View1
is the root controller, it creates and pushes;View2
that do some stuff and then creates and pushes;View3
that wants to send some results to whoever is concerned.
I see two possible solutions.
Solution 1 - Delegates
- Let
View3
declare a delegate protocolView3Delegate
. - Let
View1
conform toView3Delegate
. - When
View1
creates and pushesView2
also pass itself
to hold on to. - When
View2
creates and pushesView3
also set the delegate that was passed in step 3. - When
View3
wants 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 View2
needs to handle stuff just in order to make View1
and View3
work, not related to it's real responsibilities.
- Let
View3
declare a notification namedView3ResponseNotification
. - Let
View1
observe notifications of the nameView3ResponseNotification
. View1
creates and pushesView2
with no worries.View2
creates and pushesView3
with no worries.- When
View3
wants to send it's results it posts theView3ResponseNotification
notification.
精彩评论