How do you pass a data object from an Objective C file to a Swift file ?
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString: @"details"]){
//create the swift file and set the property I want to pass here
}
}
In the swift view:
import Foundation
import UIKit
import CoreLocation
public class SwiftViewController: UIViewController{
var passedObject:NPSCustomObject!
public override func viewDidLoad() {
}
I prefer to use NotificationCenter:
Objective C to Swift
Objective C
NSDictionary *myData = @{@"data1" : @"value1", @"data2": @"value2"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:nil userInfo:myData];
Swift
NotificationCenter.default.addObserver(forName:NSNotification.Name(rawValue: "myNotificationName"), object:nil, queue:nil, using:yourFunction)
func yourFunction(notification:Notification) -> Void {
if let extractInfo = notification.userInfo {
print(" my data: \(extractInfo["data1"])");
}
}
I found a naive way saving data with NSUserDefaults :
Objective-C Class :
NSString *myObjcData = @"from Objective-C";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:myObjcData forKey:@"data"];
[defaults synchronize];
Swift Class :
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
// Receive data ---> with NSUserdefaults
let mySwiftData: AnyObject? = prefs.valueForKey("data")
println("data is \(mySwiftData)")
}
It's not very elegant but I guarantee it works! Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With