开发者

iPhone setDelegate to a previously allocated object

开发者 https://www.devze.com 2023-03-26 07:43 出处:网络
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.

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;

  1. View1 is the root controller, it creates and pushes;
  2. View2 that do some stuff and then creates and pushes;
  3. View3 that wants to send some results to whoever is concerned.

I see two possible solutions.

Solution 1 - Delegates

  1. Let View3 declare a delegate protocol View3Delegate.
  2. Let View1 conform to View3Delegate.
  3. When View1 creates and pushes View2 also pass it self to hold on to.
  4. When View2 creates and pushes View3 also set the delegate that was passed in step 3.
  5. 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.

  1. Let View3 declare a notification named View3ResponseNotification.
  2. Let View1 observe notifications of the name View3ResponseNotification.
  3. View1 creates and pushes View2 with no worries.
  4. View2 creates and pushes View3 with no worries.
  5. When View3 wants to send it's results it posts the View3ResponseNotification notification.
0

精彩评论

暂无评论...
验证码 换一张
取 消