在 Swift 项目中包含,
CartViewModel.swift
@objc public class CartViewModel: NSObject {
let apiService: APIService
var alertMessage: String? {
didSet {
self.showAlertClosure?()
}
}
var isShow: Bool = false {
didSet {
self.updateStatus?()
}
}
@objc public var dataCount: Int {
return models.count
}
}
ListViewController.h
NS_ASSUME_NONNULL_BEGIN
@class CartViewModel;
@interface ListViewController : UIViewController
@property (nonatomic, strong) CartViewModel *viewModel;
@end
NS_ASSUME_NONNULL_END
ListViewController.m
NSLog(@"%@", self.viewModel.dataCount);
//访问任何属性都会出现此错误
Property 'dataCount' cannot be found in forward class object 'CartViewModel'
最佳答案
如果您希望能够访问 Objective-C 类的实现文件中的类的属性,则需要导入该类的 header 。通过执行 @class YourClass
简单地转发声明类仅使类型本身可见,但不公开其属性/方法。
由于 Swift 文件没有 header ,您需要导入模块的 Swift header 。
所以在你的 ListViewController.m
做
#import <YourModule/YourModule-Swift.h>
关于ios - 无法在 ObjC 中访问 Swift ViewModel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917773/