I am trying to send notification from swift file to objective c. My attempt so far:
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);
}
}
My-Bridging-Header.h
#import "ClassB.h"
But the problem is, the value is not coming to ClassB. Can anyone tell me what is wrong with this code?
You are creating an object of ClassB
AFTER posting the notification. So while the notif is posted, the ClassB
object doesn't exist. Make sure ClassB's viewDidLoad:
is called before you post the notification. Only then will ClassB
be able to listen to the notif and get the value
Updated answer for 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"
}
}
Posting notification in swift file
NotificationCenter.default.post(name: NSNotification.Name.NotificationName, object: nil)
Observe in objective-c file
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectorName:) name:NSNotification.NotificationName object:nil];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.