Swift class not registered for messages from Objective-C class using NSNotificationCenter

I am rewriting the class in Swift that I did in Objective-C, however, when I register my new Swift class as an observer, it does not respond to notifications sent to another object class c using NSNotificationCenter.

The code is as follows:

Grade A:

[[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_UI object:nil];

Class B (objective-c):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUI) name:REFRESH_UI object:nil];

- (void)refreshUI {
[self.tableView reloadData];}

Class B (fast)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshUI", name:REFRESH_UI , object: nil)

func refreshUI() {
    self.tableView.reloadData()
}

Class B works fine when writing in objective-c. What is wrong with my Swift code?

+4
source share
3 answers

, , , Obj-C Swift. :

AppDelegate:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:nil];
    NSLog(@"Finished!");

});

Swift View:

override func viewDidLoad() {

    super.viewDidLoad()
    NSLog("loaded")
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshUI", name:"refresh" , object: nil)
}


func refreshUI() {
    NSLog("Got the callback")
}

, REFRESH_UI , .

+3

Objective c :

.h:

extern NSString * DidRefreshUINotification;

.m:

NSString *DidRefreshUINotification = @"DidRefreshUINotification"; 

[[NSNotificationCenter defaultCenter] postNotificationName: DidRefreshUINotification object:nil];

Swift:

NotificationCenter.default.addObserver(self, selector: #selector(someSelector(_:)), name: .DidRefreshUI, object: nil)

DidRefreshUINotification Objective C .DidRefreshUI Swift, .

swift, Objective C: http://inessential.com/2016/09/08/adding_a_notification_observer_in_swift_

+2

I could find a mistake. This turned out to be a delegate problem from another class not related to this, where I needed to set my class B to Swift to handle the delegate. Therefore, the code I originally posted should work fine. I just switched to Swift yesterday, so forgive my ignorance.

0
source

Source: https://habr.com/ru/post/1624171/


All Articles