【问题标题】:Swift ViewModel properties can't access in ObjCSwift ViewModel 属性无法在 ObjC 中访问
【发布时间】:2020-03-14 00:17:30
【问题描述】:

在 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”

【问题讨论】:

    标签: ios objective-c swift mvvm viewmodel


    【解决方案1】:

    如果您希望能够访问 Objective-C 类的实现文件中的类的属性,则需要导入该类的头文件。只需通过 @class YourClass 转发声明类只会使类型本身可见,但不会暴露其属性/方法。

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

    所以在你的ListViewController.m

    #import <YourModule/YourModule-Swift.h>

    【讨论】:

      【解决方案2】:

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

      #import "ProductModuleName-Swift.h"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多