2012-08-09 19 views
4

我是iPhone新手。我正在嘗試實施KVO機制。UITABViewController中兩個UIViewControllers之間的KVO機制

我有什麼?

2 TabController有兩個UIViewController中,FirstViewController有一個按鈕, SecondViewController有一個UITextView

我想要什麼?

當在firstViewController中按下按鈕時,它更新成員變量,應該被secondViewController觀察到,它應該附加到UITextView。

我做了什麼?

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...");  
} 

我期望輸出什麼?

每次按下FirstViewController中的按鈕時,都應該打印字符串「.... OBSERVE VALUE FOR KEY PATH ...」。

我得到了什麼?

否OUtput。

我做錯了什麼?請幫助我

回答

3

將您的「成員變量」放入一個單獨的類文件中......即MODEL/view/controller。創建一個包含數據的單例模型對象,然後您可以從任何視圖控制器中爲模型對象創建KVO。在您的VC2

@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 

在VC1

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

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

一個更復雜的方法將使用核心數據作爲持久性:

這勾勒出了僞碼存儲並充當您的數據模型。

+0

感謝您的回覆。我對ios非常感興趣。你介意提供更多的信息,以便我可以更多地瞭解它嗎? – Whoami 2012-08-09 14:05:19

+0

編輯答案顯示一些粗暴的代碼,讓你朝着正確的方向 – CSmith 2012-08-09 14:23:57

+0

至於靜態'實例',它的指針總是一樣的嗎?既然是單身? – Honey 2016-04-14 12:06:18

相關問題