6

重複の可能性:
NSString 変数を NSNotification で他のクラスに渡す

私の質問は、Iphone の通知クラスから postNotificationName と addObserver を使用して、あるビュー コントローラーから別のビュー コントローラーにデータを渡すことができるかどうかです。

4

1 に答える 1

18

API 呼び出しの userDictionary 要素でデータを渡すことができます

NSDictionary *aDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                          anObject, @"objectName", 
                          anotherObject, @"objectId",
                          nil] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"AnythingAtAll" object:nil userInfo:aDictionary];

観察したインバウンド通知から辞書を取得できます。通知を投稿する前にオブザーバーを追加します。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyAction:) name:@"AnythingAtAll" object:nil];

これは init メソッドまたは viewDidLoad メソッドにある可能性があります

-(void)anyAction:(NSNotification *)anote
{
NSDictionary *dict = [anote userInfo];
AnyClass *objectIWantToTransfer = [dict objectForKey:@"objectName"];
}

dealloc メソッドでオブジェクトをオブザーバーとして削除する必要があることに注意してください。

[[NSNotificationCenter defaultCenter] removeObserver:self]
于 2012-04-23T20:44:35.423 に答える