質問

誰かがnsnotifcationcenterでオブジェクトプロパティを使用する方法を教えてください。それを使用して、整数値をセレクターメソッドに渡すことができます。

これが、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#>
}
役に立ちましたか?

解決

object パラメーターは通知の送信者を表し、通常は self.

余分な情報を伝えたい場合は、 NSNotificationCenter 方法 postNotificationName:object:userInfo:, 、値のarbitrary意的な辞書を取ります(自由に定義できます)。内容は実際にする必要があります NSObject インスタンス、整数などの積分タイプではないため、整数値をでラップする必要があります NSNumber オブジェクト。

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

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

他のヒント

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];
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top