无法在Objective-C View Controller中使用Swift对象的变量

时间:2018-07-01 17:22:03

标签: ios objective-c swift

从Objective-C编写的视图控制器访问Swift编写的类的变量时,我遇到了问题。

我已经创建了桥接头,并且已经成功地将Swift对象从用Swift编写的视图控制器发送到了另一个用Objective-C编写的视图控制器。问题是我想访问该对象的变量,但出现以下错误:在正向类对象'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视图控制器的方式

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视图控制器.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没有可用的任何可用变量。

1 个答案:

答案 0 :(得分:0)

要访问Objective-C类中的Swift对象,您需要将Project-Swift.h导入.m文件中,如下所示

#import "Project-Swift.h"

@implementation ObjectiveViewController 

//... other code

@end

项目是项目的名称。在您的ObjectiveViewController.m文件中添加导入语句

希望这会有所帮助