从 swift 文件发送通知并在 ios 中的 objective c 文件中接收

send notification from swift file and recieve in objective c file in ios

我正在尝试将通知从 swift 文件发送到 objective c。我目前的尝试:

ClassA.swift

    override func viewDidLoad() {
        super.viewDidLoad()

        let containerDict:[String:AnyObject] =  ["vwConatinerFrameWidth": vwContainer.frame.size.width, "vwConatinerFrameHeight": vwContainer.frame.size.height]

        NSNotificationCenter.defaultCenter().postNotificationName("ContainerFrame", object: self, userInfo: containerDict)

        let classB = ClassB(nibName: "ClassB", bundle: nil)

        classB.willMoveToParentViewController(self)

        self.vwContainer.addSubview(classB.view)

        self.addChildViewController(classB)
        classB.didMoveToParentViewController(self)

    }

ClassB.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(containeFrameRecieved:)
                                                 name:@"ContainerFrame"
                                               object:nil];
}

- (void)containeFrameRecieved:(NSNotification *)note {
    NSDictionary *theData = [note userInfo];

    if (theData != nil) {

        CGFloat containerFrameWidth = [[theData objectForKey:@"vwConatinerFrameWidth"] floatValue];
        CGFloat containerFrameHeight = [[theData objectForKey:@"vwConatinerFrameHeight"] floatValue];

        NSLog(@"Width:%f and Height: %f",containerFrameWidth,containerFrameHeight);
    }

}

我的桥接-Header.h

#import "ClassB.h"

但问题是,这个值没有传到ClassB。谁能告诉我这段代码有什么问题吗?

您正在 post 通知后创建 ClassB 对象。因此,虽然通知是 posted,但 ClassB 对象不存在。确保在 post 通知之前调用 ClassB 的 viewDidLoad:。只有这样ClassB才能监听到notif并得到值

Swift 4.1

的更新答案
// Notification name for swift
extension NSNotification.Name {
    static let NotificationName = Notification.Name(rawValue: "NotificationName")
}

// Notification name for Objective-C
@objc public extension NSNotification {
    public static var NotificationName: String {
        return "NotificationName"
    }
}

在 swift 文件中发布通知

NotificationCenter.default.post(name: NSNotification.Name.NotificationName, object: nil)

在objective-c文件中观察

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorName:) name:NSNotification.NotificationName object:nil];