繁体   English   中英

从swift文件发送通知并在ios中接收目标c文件

[英]send notification from swift file and recieve in objective c file in ios

我正在尝试将通知从swift文件发送到目标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上。 谁能告诉我这段代码有什么问题吗?

发布通知后,您将创建ClassB的对象。 因此,在发布通知时, ClassB对象不存在。 发布通知之前,请确保已调用ClassB的viewDidLoad: 只有这样, ClassB才能收听通知并获取值

更新了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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM