Swift ViewModel属性无法在ObjC中访问

在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); 

//访问任何属性都会出现此错误

  

在正向类对象'CartViewModel'中找不到属性'dataCount'

xwhses 回答:Swift ViewModel属性无法在ObjC中访问

如果要能够访问Objective-C类的实现文件内的类的属性,则需要导入该类的头。通过执行@class YourClass向前简单地声明该类只会使该类型本身可见,但不会公开其属性/方法。

由于Swift文件没有标头,因此您需要导入模块的Swift标头。

因此,在您的ListViewController.m中做

#import <YourModule/YourModule-Swift.h>

,

在Objective-C实现中,您需要导入Xcode生成的Swift头文件。将此添加到您的导入中,用目标名称替换ProductModuleName

#import "ProductModuleName-Swift.h"

本文链接:https://www.f2er.com/3079870.html

大家都在问