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;
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.
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 :)
User Info is a key => value dictionary:
userInfo:@{[NSNumber numberWithInt:option2]:kNotificationName}];
Here you have value => key. Try this:
@{kNotificationName:@{option2}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.