我在从 Objective-C 编写的 View Controller 访问 Swift 编写的类的变量时遇到问题。
我已经创建了桥接 header ,并且已成功将 Swift 对象从用 Swift 编写的 View Controller 发送到另一个用 Objective-C 编写的 View Controller 。问题是我想访问对象的变量,但出现以下错误:在前向类对象“className”中找不到属性“variableName”。
这是我试图访问其变量的类:
import Foundation
import UIKit
import SwiftyJSON
@objcMembers
class SwiftObject: NSObject {
// MARK: - Variables
var id: String
var name: String
var contact: SwiftSubObjectA
var location: SwiftSubObjectB
var categories: [SwiftSubObjectC] = []
// MARK: - Initializers
init(withJSON json: JSON) {
self.id = json["id"].stringValue
self.name = json["name"].stringValue
self.contact = SwiftSubObjectA(withJSON: json["contact"])
self.location = SwiftSubObjectB(withJSON: json["location"])
for categoryJSON in json["categories"].arrayValue {
categories.append(SwiftSubObjectC(withJSON: categoryJSON))
}
}
}
这就是我将对象发送到 Objective-C View Controller 的方式
class SwiftViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let objectiveVC.object = segue.destination as? ObjectiveViewController else { return }
guard let object = sender as? SwiftObject else { return }
objectiveVC.object = object
}
}
最后,这是 Objective-C View Controller .h 文件:
#import <UIKit/UIKit.h>
@class SwiftObject;
@interface ObjectiveViewController : UIViewController
@property (strong, nonatomic) SwiftObject * _Nonnull object;
@end
和 .m 文件:
#import "ObjectiveViewController.h"
#import "Project-Bridging-Header.h"
@interface ObjectiveViewController ()
@end
@implementation ObjectiveViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@", self.object.name);
// Do any additional setup after loading the view.
}
@end
问题是 self.object 没有任何可用的变量。
最佳答案
为了访问 Objective-C 类中的 Swift 对象,您需要在 .m 文件中导入 Project-Swift.h
,如下所示
#import "Project-Swift.h"
@implementation ObjectiveViewController
//... other code
@end
Project 是项目的名称。在 ObjectiveViewController.m
文件中添加导入语句
希望这有帮助
关于ios - 无法在 Objective-C View Controller 中使用 Swift 对象的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125421/