Reputation: 123
I am facing a problem accessing variables of a class written in Swift from a view controller written in Objective-C.
I have already created the Bridging Header and I have successfully sent the Swift object from a view controller written in Swift to another one written in Objective-C. The problem is that I want to access the variables of the object but I get the following error: Property 'variableName' cannot be found in forward class object 'className'.
Here is the class which I am trying to access its variables:
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))
}
}
}
And this is how I am sending the object into the 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
}
}
Finally, this is the Objective-C view controller .h file:
#import <UIKit/UIKit.h>
@class SwiftObject;
@interface ObjectiveViewController : UIViewController
@property (strong, nonatomic) SwiftObject * _Nonnull object;
@end
and the .m file:
#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
The problem is that the self.object does not have any available variables to be used.
Upvotes: 0
Views: 336
Reputation: 20369
In order to access Swift object in your Objective-C Class you need to import Project-Swift.h
in your .m file as shown below
#import "Project-Swift.h"
@implementation ObjectiveViewController
//... other code
@end
Project is the name of the project. Add the import statement in your ObjectiveViewController.m
file
Hope this helps
Upvotes: 1