Reputation: 1649
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() {
}
Upvotes: 4
Views: 6966
Reputation: 1284
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.
Upvotes: 6
Reputation: 539
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"])");
}
}
Upvotes: 8
Reputation: 126117
If the "details" segue is set up in the storyboard as passing to a view controller of type SwiftViewController
(which it should be for the workflow you've hinted at), you don't create an instance of the latter — the segue has already done that for you. You can access it inside prepareForSegue
as segue.destinationViewController
.
Assuming your project is already set up with the proper headers for bridging Swift to (Obj)C, you just need to cast segue.destinationViewController
to the type you're working with so you can access its members. For example:
if([[segue identifier] isEqualToString: @"details"]){
SwiftViewController *vc = (SwiftViewController *)segue.destinationViewController;
vc.passedObject = // put your instance of NPSCustomObject here
}
Upvotes: 5