如何将数据对象从Objective C文件传递到Swift文件?
- (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
}
}
在快速视图中:
import Foundation
import UIKit
import CoreLocation
public class SwiftViewController: UIViewController{
var passedObject:NPSCustomObject!
public override func viewDidLoad() {
}
答案 0 :(得分:6)
我更喜欢使用NotificationCenter:
目标C到Swift
目标C
NSDictionary *myData = @{@"data1" : @"value1", @"data2": @"value2"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:nil userInfo:myData];
夫特
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"])");
}
}
答案 1 :(得分:5)
我发现了一点点' hack'使用NSUserDefaults保存数据:
Objective-C类:
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)")
}
它不是很优雅,但我保证它有效! 希望它有所帮助。
答案 2 :(得分:4)
如果"详情" segue在故事板中设置为传递给SwiftViewController
类型的视图控制器(它应该用于您已经暗示的工作流程),您不会创建后者的实例 - segue已经为你做了这件事。您可以prepareForSegue
内的segue.destinationViewController
访问它。
假设您的项目已经set up with the proper headers for bridging Swift to (Obj)C,您只需要将segue.destinationViewController
投射到您正在使用的类型,以便您可以访问其成员。例如:
if([[segue identifier] isEqualToString: @"details"]){
SwiftViewController *vc = (SwiftViewController *)segue.destinationViewController;
vc.passedObject = // put your instance of NPSCustomObject here
}