objective c - delegation and passing data back from childViewController -


i have been struggling few days , have received valuable on way s.o. have made simplest possible project reduce possibilities of being typo. project is, viewcontroller holds container view hooked childviewcontroller. "parent" viewcontroller set delegate of childviewcontroller. in viewdidload of child passing value string. string should passed on parent , printed on console. here files.

viewcontroller.h

#import <uikit/uikit.h> #import "childviewcontroller.h"  @interface viewcontroller : uiviewcontroller <childviewcontrollerdelegate>  @end 

viewcontroller.m

#import "viewcontroller.h"  @interface viewcontroller ()  @property nsstring *myvalueretrieved;  @end  @implementation viewcontroller  - (void)viewdidload {     [super viewdidload];     childviewcontroller *controller = [self.storyboard instantiateviewcontrollerwithidentifier:@"childvc"];      controller.delegate = self;      nslog(@"here value: %@",self.myvalueretrieved); }  - (void)didreceivememorywarning {     [super didreceivememorywarning]; }  - (void) passvalue:(nsstring *)thevalue{      self.myvalueretrieved = thevalue; }  @end 

childviewcontroller.h

#import <uikit/uikit.h>  @protocol childviewcontrollerdelegate;  @interface childviewcontroller : uiviewcontroller  @property (weak)id <childviewcontrollerdelegate> delegate;  @end  @protocol childviewcontrollerdelegate <nsobject>  - (void) passvalue:(nsstring*) thevalue;  @end 

childviewcontroller.m

#import "childviewcontroller.h"  @interface childviewcontroller () @property nsarray *colors; @end  @implementation childviewcontroller  - (void)viewdidload {     [super viewdidload];      [self.delegate passvalue:@"hello"]; }  - (void)didreceivememorywarning {     [super didreceivememorywarning]; }  @end 

am right think when app launched, console should log following message: "here value: hello". doing wrong in terms of logically not getting delegation or silly typo somewhere? tx

you're assuming view loaded when view controller instantiated. that's how works. view gets loaded when it's needed (like add parent view).

but can force view load , make work. call -loadviewifneeded on child view controller right after setting delegate. want:

controller.delegate = self; [controller loadviewifneeded]; nslog(@"here value: %@",self.myvalueretrieved); 

or, if want call delegate in viewdidload, you'd need move nslog -passvalue: method, since primary view controller's viewdidload method have finished running.


Comments