如何使用 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传递给另一个类。

121453 次浏览

您必须使用“ userInfo”变量并传递一个包含 messageTotal 整数的 NSDictionary 对象:

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);
}
}

在提供的解决方案的基础上,我认为展示一个传递自定义数据对象的示例可能会有所帮助(我在这里按照问题将其称为“ message”)。

甲类(寄件人) :

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 迅捷2版本

正如@Johan Karlsson 指出的... ... 我做错了。以下是使用 NSNotificationCenter 发送和接收信息的正确方法。

首先,我们查看 postNotificationName 的初始化程序:

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

来源

我们将使用 userInfo参数传递信息。[NSObject : AnyObject]类型是从 目标 C保留下来的。因此,在 Swift 领域,我们所需要做的就是传递一个 Swift 字典,其中包含从 NSObject派生的键和可以是 AnyObject的值。

根据这些知识,我们创建了一个字典,并将其传递给 object参数:

 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 5

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"]
}

额外奖励(你绝对应该这么做!) :

.someNotificationName代替 Notification.Name("SomeNotificationName"):

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

Notification.Key.key0Notification.Key.key1代替 "key0""key1":

extension Notification {
enum Key: String {
case key0
case key1
}
}

为什么我一定要这样做? 为了避免代价高昂的错误,享受重命名,享受找到使用等..。

Swift 5.1自定义对象/类型

// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
static let yourNotificationName = Notification.Name("yourNotificationName")
}




// MARK: - CustomObject
class YourCustomObject {
// Any stuffs you would like to set in your custom object as always.
init() {}
}


// MARK: - Notification Sender Class
class NotificatioSenderClass {


// Just grab the content of this function and put it to your function responsible for triggering a notification.
func postNotification(){
// Note: - This is the important part pass your object instance as object parameter.
let yourObjectInstance = YourCustomObject()
NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
}
}


// MARK: -Notification  Receiver class
class NotificationReceiverClass: UIViewController {
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Register your notification listener
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
}


// MARK: - Helpers
@objc private func didReceiveNotificationWithCustomObject(notification: Notification){
// Important: - Grab your custom object here by casting the notification object.
guard let yourPassedObject = notification.object as? YourCustomObject else {return}
// That's it now you can use your custom object
//
//


}
// MARK: - Deinit
deinit {
// Save your memory by releasing notification listener
NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
}








}