簡體   English   中英

從NSNumber到枚舉的錯誤值

[英]Wrong value from NSNumber to enum

我正在發送enum里面的通知:

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

接收它:

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

問題是myState有錯誤的值。 當我打印通知我得到:

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

但myState == option0。

為什么會這樣?

編輯:

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

嘗試編寫這樣的枚舉函數: -

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

並打印個人信息,例如您的通知輸出和myState對象的輸出。

我不會使用NSNotification(因為你已經發現,沒有編譯時檢查,並且在很多情況下使用非常麻煩)。 相反,一個更好的選擇可能是使用像Tolo這樣的事件總線 - 非常容易使用並自動刪除dealloc上的訂閱者。 你會寫:

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

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

看看這個。

看起來你得到了價值和鑰匙切換。

字典應該像這樣使用: @{key:value}

嘗試這個:

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

希望能幫助到你 :)

用戶信息是一個鍵=>值字典:

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

這里有值=>鍵。 嘗試這個:

@{kNotificationName:@{option2}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM