73

NSNotifcationCenter で object プロパティを使用する方法を教えてください。これを使用して、セレクター メソッドに整数値を渡したいと考えています。

これは、UI ビューで通知リスナーを設定する方法です。整数値を渡したいので、 nil を何に置き換えるかわかりません。

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


- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

このように別のクラスから通知をディスパッチします。この関数には、index という名前の変数が渡されます。何らかの方法で通知を開始したいのは、この値です。

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}
4

2 に答える 2

106

このobjectパラメーターは、通知の送信者を表します。通常はselfです。

追加情報を渡したい場合は、NSNotificationCenterメソッドを使用する必要があります。このメソッドpostNotificationName:object:userInfo:は、任意の値のディクショナリ(自由に定義できます)を取ります。NSObject内容は、整数などの整数型ではなく、実際のインスタンスである必要があるため、整数値をNSNumberオブジェクトでラップする必要があります。

NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];
于 2010-11-30T10:51:40.640 に答える
83

このobjectプロパティはそれに適していません。代わりに、次のuserinfoパラメーターを使用します。

+ (id)notificationWithName:(NSString *)aName 
                    object:(id)anObject 
                  userInfo:(NSDictionary *)userInfo

userInfoご覧のとおり、通知とともに情報を送信するための NSDictionary です。

あなたのdispatchFunction方法は代わりに次のようになります:

- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}

あなたのreceiveEvent方法は次のようになります:

- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}
于 2010-11-30T10:48:23.410 に答える