0

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;
Nat
  • 12,032
  • 9
  • 56
  • 103

4 Answers4

1

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.

D-eptdeveloper
  • 2,430
  • 1
  • 16
  • 30
1

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.

Ephraim
  • 2,234
  • 1
  • 21
  • 18
  • Interesting, I've never seen this. Will copy it somewhere and try to use later. Thanks for snippet. – Nat Sep 13 '13 at 09:48
0

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 :)

ThomasCle
  • 6,792
  • 7
  • 41
  • 81
0

User Info is a key => value dictionary:

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

Here you have value => key. Try this:

@{kNotificationName:@{option2}]
Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71