Scott
Scott

Reputation: 39

Why is this delegate - protocol not responding?

I have a method called dateSelectViewController declared in my .h file as a protocol:

@class DateSelectViewController;
@protocol DateSelectViewControllerDelegate 

- (void)dateSelectViewController:(DateSelectViewController *)sender
                         theDate:(id)stringDate;

@end

Below the protocol, I'm declaring a delegate:

@property (nonatomic, weak) id <DateSelectViewControllerDelegate> delegate;

and in the implementation file, I synthesize the delegate, and I send a message to the delegate when the done button is pressed in my view:

- (IBAction)DonePressed:(id)sender {
    NSDate *chosen = [datePicker date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSString *formatedDate = [formatter stringFromDate:chosen];

    //sending a message to the delegate
    [self.delegate dateSelectViewController:self theDate:formatedDate];

    [self.navigationController popViewControllerAnimated:YES];
}

In the .h file that's being delegated to, I'm importing the delegators .h file. And in the .m file I'm conforming to the protocol:

@interface MakePlantTVC ()<DateSelectViewControllerDelegate>
- (void)dateSelectViewController:(DateSelectViewController *)sender
                     theDate:(id)stringDate
{
    self.displayDate.text = stringDate;
    NSLog(@"delegate working");
}

For some reason the this is working at all. When the done button is pressed in my delegators class, the button does as it's supposed to and pops the view controller but it's like the message is never sent to the delegate. At first I thought I could be sending a message to nil but its' of type id, so that shouldn't be the case. Why is the message not being sent?

Upvotes: 0

Views: 2808

Answers (1)

Matt Melton
Matt Melton

Reputation: 2643

A few things came to mind

  • Have you set the delegate? It might sound stupid but when a delegate doesn't work it's because I forget or lose the IB connection, 90% of the time.
  • Does your weak object expire? A weak object is nil'ed - therefore you're performing a delegate operation on 'nothing' - perhaps you want something more retainy or an NSNotification

Other things I practice with delegates that might be useful

  • Use assert based programming? When you have a protocol with required functions, it's worth asserting, ie: NSAssert(delegate, @"Error, delegate not set!");
  • Check to see if the delegate responds to the selector
  • Dispatch delegate calls asynchronously with GCD, ie:

    dispatch_async(dispatch_get_main_queue(), ^{
      if ([delegate_ respondsToSelector:@selector(updateUI:)]) 
        [delegate_ updateUI:self];
    });
    

Hope this helps!

Upvotes: 6

Related Questions