objective c - OS X Delegate set label from other window (Xcode) -
i'm quite new mac programming (not objective c).
i'm developing small application, shows data , opens second window on button press. in second window textfield , submit button. if submit button pressed, window should close + value of textfield needs passed first window.
i think best method simple delegate. tried can't change label in first window using second window.. delegate seems work can call methods other class , send data it. won't change label.
as first try on delegates, im pretty sure i've done stupid here^^
or there better solution? can't complicated change label second window.. right?
viewcontroller.h (firstcontroller)
#import <cocoa/cocoa.h> @class viewcontroller; @protocol viewcontrollerdelegate -(void)sayhello:(viewcontroller *)viewcontroller; @end @interface viewcontroller : nsviewcontroller { iboutlet nstextfield *txtlabel; } @property (nonatomic, assign) id delegate; -(void)hellodelegate; -(void)recivevar:(nsstring*)strvar; @end
viewcontroller.m (firstcontroller)
#import "viewcontroller.h" @implementation viewcontroller @synthesize delegate; -(id)init { self = [super init]; return self; } - (void)viewdidload { [super viewdidload]; txtlabel.stringvalue=@"test"; } -(void)hellodelegate { [delegate sayhello:self]; } -(void)recivevar:(nsstring*)strvar { nslog(@"recived: %@", strvar); txtlabel.stringvalue=strvar; // dosent work!! } @end
secondcontroller.h
#import <cocoa/cocoa.h> #import "viewcontroller.h" @interface secondcontroller : nsviewcontroller <viewcontrollerdelegate> { iboutlet nstextfield *txtfield; } -(ibaction)submit:(id)sender; @end
secondcontroller.m
#import "firstcontroller.h" @implementation secondcontroller -(void)viewdidload { [super viewdidload]; viewcontroller *custom = [[viewcontroller alloc] init]; // assign delegate custom.delegate = self; [custom hellodelegate]; } -(void)sayhello:(viewcontroller *)viewcontroller { nslog(@"hiya!"); } -(ibaction)submit:(id)sender { nsstring *txtval= txtfield.stringvalue; nslog(@"submit: %@", txtval); viewcontroller *custom = [[viewcontroller alloc] init]; // assign delegate custom.delegate = self; [custom recivevar:txtval]; } @end
log output:
- hiya!
- submit: test
- recived: test
(so guess delegate works..)
solved. (thanks phillip mills)
nsnotification way simpler , efficient delegates in case.
viewcontroller.m
[...] - (void)viewdidload { [super viewdidload]; txtlabel.stringvalue=@"test"; [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(handleupdateddata:) name:@"dataupdated" object:nil]; } -(void)handleupdateddata:(nsnotification *)notification { nslog(@"recieved %@", notification); txtlabel.stringvalue=[notification object]; }
secondcontroller.m
-(ibaction)submit:(id)sender { nsstring *txtval= txtfield.stringvalue; nslog(@"submit: %@", txtval); [[nsnotificationcenter defaultcenter] postnotificationname:@"dataupdated" object:txtval]; }
Comments
Post a Comment