今天,我尝试在我的 Javascript 代码中使用实现单例模式的自定义 Swift 类。我已经创建了 native 模块,但今天我遇到了这个错误:“ fatal error :使用未实现的初始化程序 'init()' for class”
我猜是因为单例模式,但我无法理解我的错误......
这是我的代码:
AnalyticsTracker.swift
import Foundation
import Tracker
@objc(AnalyticsTracker)
class AnalyticsTracker: NSObject {
static let shared = AnalyticsTracker(tracker: ATInternet.sharedInstance.defaultTracker)
// MARK: -
let tracker: Tracker
// Initialization
private init(tracker: Tracker) {
self.tracker = tracker
}
@objc
func viewScreen(screen: String) {
self.tracker.screens.add(screen).sendView()
}
@objc
func sendTouch(clickName: String, chapter1: String, chapter2: String, chapter3: String, level2: Int) {
let gesture = self.tracker.gestures.add(clickName, chapter1: chapter1, chapter2: chapter2, chapter3:chapter3)
gesture.level2 = level2
gesture.sendTouch()
}
}
以及将我的类(class)导出到我的 react-native 应用程序的模块:
AnalyticsTracker.m
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(AnalyticsTracker, NSObject)
RCT_EXTERN_METHOD(
sendTouch:
(NSString*)clickName
(NSString*)chapter1
(NSString*)chapter2
(NSString*)chapter3
(int)level2
)
@end
删除导出模块后错误消失。我真的不明白这个错误是什么意思......
如果有人有想法,将不胜感激
问题在于 React Native 桥接机制。 AFAIK 它不支持自定义初始化。作为一种解决方法,您可以创建一个在其导出方法中使用 AnalyticsTracker.shared 的帮助器类:
// RNAnalyticsTracker.swift
import Foundation
@objc(RNAnalyticsTracker)
class RNAnalyticsTracker: NSObject {
@objc
func viewScreen(screen: String) {
AnalyticsTracker.shared.viewScreen(screen: screen)
}
@objc
func sendTouch(clickName: String, chapter1: String, chapter2: String, chapter3: String, level2: Int) {
AnalyticsTracker.shared.sendTouch(clickName: clickName, chapter1: chapter1, chapter2: chapter2, chapter3: chapter3, level2: level2)
}
}
来源引用:https://gist.github.com/harveyconnor/7b0e778effaae302f512485c18881569
关于ios - React-native 桥接与 Swift 单例自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472700/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |