首页 > 解决方案 > 为什么我必须将我的第二个参数标记为对 swift 桥接函数的本机反应

问题描述

假设我有以下 Swift 类:

@objc(ExampleClass)
  class ExampleClass: NSObject {
  init() {}
  @objc func exampleMethod(_ message: String, _ properties: [String: Any]? = nil) -> Void {}
}

以及以下标题:

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(ExampleClass, NSObject)

RCT_EXTERN_METHOD(exampleMethod:(NSString *)name (NSDictionary *)properties)
@end

然后我使用以下 React Native 代码调用它:

import { NativeModules } from 'react-native'

NativeModules.ExampleClass.exampleMethod('example', {'hello': 'world'})

这会导致以下错误消息:

ExceptionsManager.js:73 Exception 'exampleMethod: is not a recognized Objective-C method.' was thrown while invoking trackEvent on target SegmentTracker with params (
    "example",
        {
        hello = world;
    }
)

但是,如果我将函数签名更改为这样标记:

@objc func exampleMethod(_ message: String, withProperties properties: [String: Any]? = nil) -> Void {}
    }

并像这样调整 RCT_EXTERN_METHOD 函数:

RCT_EXTERN_METHOD(exampleMethod:(NSString *)name withProperties:(NSDictionary *)properties)

为什么必须标记第二个参数?第一个怎么没有?

标签: objective-cswiftreact-native

解决方案


推荐阅读