문제

I'm sending a notification with enum inside:

[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTitle object:nil userInfo:@{[NSNumber numberWithInt:option2]:kNotificationName}];

And receiving it:

- (void)myAction:(NSNotification *)notification {
MyState myState = (MyState)[[[notification userInfo] objectForKey:kNotificationName] integerValue];

The problem is that myState has wrong value. When i print notification i get:

Printing description of notification:
NSConcreteNotification 0x123456 {name = notificationTitle; userInfo = {2 = notificationName;}}

But myState == option0.

Why it's happening like this?

EDIT:

typedef enum myStates {
  option0,
  option1,
  option2,
  option3
} MyState;
도움이 되었습니까?

해결책 3

It looks like you got the value and key switched around.

The dictionary should be used like this: @{key:value}

Try this:

[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTitle object:nil userInfo:@{kNotificationName:[NSNumber numberWithInt:option2]}];

Hope it helps :)

다른 팁

try to write your enum function like this:-

typedef enum myStates {
  option0 = 0,
  option1,
  option2,
  option3
} MyState;

and print both as individual like what output your notification has and what output your myState object has.

I wouldn't use NSNotification (as you've found out, no compile time check, and really cumbersome to use in many cases like this). Instead, a better alternative maybe to use an event bus like Tolo -- very easy to use and automatic removing of subscribers on dealloc. You would just write:

@interface EventStateChanged : NSObject
@property(nonatomic) MyState state;
@end

SUBSCRIBE(EventStateChanged)
{
MyState state = event.state;
    // Do something with state.
}

Check it out.

User Info is a key => value dictionary:

userInfo:@{[NSNumber numberWithInt:option2]:kNotificationName}];

Here you have value => key. Try this:

@{kNotificationName:@{option2}]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top