1

I have a UIViewController(1), I press on a view in that controller and it then push's another UIViewController(2) with a full screen UITableView in it.

I then press on a cell in the UITableView and want to pass back to UIViewController(1) a string in the UITableView. I have tried using the below delegete method but it doesn't work, please can somebody advise.

UIViewController2.h
@protocol SecondDelegate <NSObject>
-(void) secondViewControllerDismissed:(NSString *)stringForFirst;
@end

@interface ViewController2 : UIViewController
{
    id myDelegate;
}
@property (nonatomic, assign) id<SecondDelegate> myDelegate;
@end

and

UIViewController2.m (inside didSelectRowAtIndexPath)
    [self.myDelegate secondViewControllerDismissed:@"the string I'm passing"];

and

UIViewController1.h
import "ViewController2.h"
    @interface ViewController1 : UIViewController <SecondDelegate>

@end

and

UIViewController1.m
- (void)secondViewControllerDismissed:(NSString *)stringForFirst
{
    NSString *myString = stringForFirst; 
    self.myLabel.text = myString;
}
James Walker
  • 69
  • 1
  • 8

1 Answers1

1

A few things:

  • remove id myDelegate; inside your @interface ViewController2
  • change your @property (nonatomic, assign) id... to @property (nonatomic, weak) id..., that is just safer (see why)

Regarding your question: you present the view via a segue!? Therefore you need to overwrite the prepareForSegue method, extract the destinationViewController from the segue and set its delegate property to self. Without that, your ViewController2 never gets a valid delegate set. All that needs to be done in the viewController presenting the ViewController2:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    [super prepareForSegue:segue sender:sender];
    if ([segue.identifier isEqualToString:@"yourCustomSegueIdentifier"]) {
        ViewController2 *controller = (ViewController2*)segue.destinationViewController;
        controller. myDelegate = self;
    }
}

Either set an identifier of your segue in the storyboard and use the same identifier in the ode above or remove the if all together (unclean).

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137