2012-02-03 10 views
0

私はプログラムで作成される2つのビューを持っています。それらをview1とview2と名づけましょう。 view1にはピッカーとボタンがあります。このアイデアは、ユーザーが値を選択し、選択されたボタンの値を押してview2からアクセス可能なときです。このため私はNSNotificationCenterを使用します。ここにいくつかのコードがあります。iOS:ビュー間でデータを渡す

view1.m

-(void)registerNotification 
{ 
    NSDictionary *dict = [NSDictionary dictionaryWithObject:self.selectedOption forKey:@"data"]; 

    [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"pickerdata" 
    object:self 
    userInfo:dict]; 
} 

-(void)loadSecondView 
{ 
    self.secondView = [[secondViewController alloc]init]; 
    [self.view addSubview:self.secondView.view]; 
    [self registerNotification]; 
    [self.secondView release]; 
} 

view2.m

-(id)init 
{ 
    if(self = [super init]) 
    { 
    [[NSNotificationCenter defaultCenter] 
     addObserver:self 
     selector:@selector(reciveNotification:) 
     name:@"pickerdata" object:nil]; 
    } 
    return self; 
} 


-(void)reciveNotification:(NSNotification *)notification 
{ 
    if([[notification name] isEqualToString:@"pickerdata"]) 
    { 
     NSLog(@"%@", [NSString stringWithFormat:@"%@", [[notification userInfo] objectForKey:@"data"]]); // The output of NSLog print selected value 

     // Here is assignment to ivar 
     self.selectedValue = [NSString stringWithFormat:@"%@", [[notification userInfo] objectForKey:@"data"]]; 
    } 
} 

問題はここから始まります。その値に関係するロジックは、loadViewメソッドで実装されます。問題は、reciveNotificationメソッドの前にloadViewが実行され、selectedValueに必要な情報がまだ含まれていないことです。 NSNotificationCenterから提供された情報をloadViewメソッドからアクセスできるようにするにはどうすればよいですか?

+0

はおそらく、私は質問のポイントを逃していますが、あなたはどのようにそのビュー負荷に影響を及ぼしビューにデータを渡したい場合は、その理由だけでカスタム初期化子を作ってみませんか?' - (void)loadSecondViewWithOption:(id)オプション;' view1または ' - (id)initWithFrame:(CGFrame)フレームオプション:(id)オプション; – modocache

答えて

2

私はあなたの質問を完全に理解しているかどうかわかりませんが、通知を処理する代わりに直接viewControllerに値を渡す方が簡単ではないでしょうか?

-(void)loadSecondView 
{ 
    self.secondView = [[secondViewController alloc]init]; 
    self.secondView.selectedValue = self.selectedOption; 
    [self.view addSubview:self.secondView.view]; 
    [self.secondView release]; 
} 
+0

ありがとう!それはトリックでした! – Profo

関連する問題