Как передать объект с помощью NSNotificationCenter



Я пытаюсь передать объект из моего делегата приложения в приемник уведомлений в другом классе.



Я хочу передать целое число messageTotal. Прямо сейчас у меня есть:



В Приемник:



- (void) receiveTestNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissSheet) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"eRXReceived" object:nil];


в классе, который делает уведомление:



[UIApplication sharedApplication].applicationIconBadgeNumber = messageTotal;
[[NSNotificationCenter defaultCenter] postNotificationName:@"eRXReceived" object:self];


но я хочу передать объект messageTotal в другой класс.

546   4  

4 ответов:

вам нужно будет использовать вариант "userInfo" и передать объект NSDictionary, содержащий целое число messageTotal:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

на принимающей стороне вы можете получить доступ к словарю userInfo следующим образом:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

основываясь на решении, я подумал, что было бы полезно показать пример передачи собственного пользовательского объекта данных (который я упомянул здесь как "сообщение" в соответствии с вопросом).

класс " а " (отправителя):

YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];

класс B (приемник):

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}

#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
    NSDictionary *dict = notification.userInfo;
    YourDataObject *message = [dict valueForKey:@"message"];
    if (message != nil) {
        // do stuff here with your message data
    }
}

Swift 2 Version

как указал @Johan Karlsson... Я делал это неправильно. Вот правильный способ отправки и получения информации с помощью NSNotificationCenter.

во-первых, мы смотрим на инициализатор для postNotificationName:

init(name name: String,
   object object: AnyObject?,
 userInfo userInfo: [NSObject : AnyObject]?)

источник

мы будем передавать нашу информацию с помощью userInfo парам. Элемент [NSObject : AnyObject] тип-это удержание от С. Итак, в Swift Земля, все, что нам нужно сделать, это передать в Swift словарь, который имеет ключи, полученные из NSObject и значения, которые могут быть AnyObject.

С этим знанием мы создаем словарь, который мы проходим в :

 var userInfo = [String:String]()
 userInfo["UserName"] = "Dan"
 userInfo["Something"] = "Could be any object including a custom Type."

затем мы передаем словарь в наш параметр объекта.

отправитель

NSNotificationCenter.defaultCenter()
    .postNotificationName("myCustomId", object: nil, userInfo: userInfo)

Приемник Класс

Сначала мы должны убедиться, что наш класс наблюдение за уведомлением

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("btnClicked:"), name: "myCustomId", object: nil)   
}

затем мы можем получить наш словарь:

func btnClicked(notification: NSNotification) {
   let userInfo : [String:String!] = notification.userInfo as! [String:String!]
   let name = userInfo["UserName"]
   print(name)
}

Swift 4

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

бонус (вы должны обязательно сделать!):

заменить Notification.Name("SomeNotificationName") С .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

заменить "key0" и "key1" С Notification.Key.key0 и Notification.Key.key1:

extension Notification.Key {
    static let key0 = "key0"
    static let key1 = "key1"
}

почему я должен это делать ? Чтобы избежать дорогостоящих ошибок опечатки, наслаждайтесь переименованием, наслаждайтесь поиском использования и т. д...

Comments

    Ничего не найдено.