KVO mechanism between two UIViewControllers in a UITABViewController

I am new to iPhone. I am trying to implement a KVO mechanism.

What I have?

two TabController with two UIViewController, FirstViewController has a button, SecondViewController has a UITextView

What I want?

When a button is clicked in the first control, it updates the member variable that secondViewController should observe, and it must be added to the UITextView.

What I've done?

FirstViewController.h

@interface FirstViewController : UIViewController { IBOutlet UIButton *submitButton; } -(IBAction)submitButtonPressed; @property (retain) NSString* logString; @end 

FirstViewController.m

 -(IBAction)submitButtonPressed { NSLog (@" Submit Button PRessed "); self.logString = @"... BUtton PRessed and passing this information "; } 

SecondViewController.h

 @interface SecondViewController : UIViewController { IBOutlet UITextView *logView; } @property (nonatomic, strong) UITextView *logView; @end 

SecondViewController.m

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { ...... NSArray *vControllers = [self.tabBarController viewControllers]; FirstViewController *fvc = [vControllers objectAtIndex:0]; [fvc addObserver:self forKeyPath:@"logString" options:NSKeyValueObservingOptionNew context:NULL]; return self; } -(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog (@".... OBSERVE VALUE FOR KEY PATH..."); } 

What result do I expect?

The string ".... MONITORING THE VALUE FOR THE KEY TO THE PATH ..." should be printed every time I click the button in the FirstViewController.

What am I getting?

No OUtput.

What am I doing wrong? Please help me

+4
source share
1 answer

put your "member variable" in a separate class file ... i.e. MODEL / view / controller. Make a singleton model object that stores your data, then you can KVO, which models the object from any view controller.

This is the pseudo code:

  @interface MyDataModel: NSObject { NSString *logString; } @property (nonatomic,retain) NSString *logString; @end @implementation MyDataModel @synthesize logString; + (MyDataModel *) modelObject { static MyDataModel *instance = nil; static dispatch_once_t once; dispatch_once(&once, ^{ if (instance == nil) { instance = [[self alloc] init]; } }); return (instance); } @end 

in your vc1

 MyDataModel *model = [MyDataModel modelObject]; [model setLogString:@"test"]; 

in your vc2

 [model addObserver:self forKeyPath:@"logString" options:0 context:NULL]; 

a more sophisticated approach would be to use Core Data as a permanent store and act as your data model.

+3
source

All Articles