基于0.18.1
Async batched bridge used to communicate with the JavaScript application.
分析Objective-C和JavaScript的通信机制。
Bridge承担以下工作(或者提供接口):
A: 执行JavaScript代码
1 - (void)enqueueJSCall:(NSString *)moduleDotMethod args:(NSArray *)args;
B: 管理"bridge module"
1 - (id)moduleForName:(NSString *)moduleName;
2 - (id)moduleForClass:(Class)moduleClass;
C: 创建 JavaScript 执行器
1 - (void)initModules
2 {
3 ......
4 _javaScriptExecutor = [self moduleForClass:self.executorClass];
在React-Native Based的工程中, 我们看到在AppDelegate.m文件中有以下代码:
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"WaterApp"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [UIColor blackColor];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
之所以可以使用JS来进行iOS App开发,RCTRootView类是可以进行探索其原因的起点。
接下来浏览类RCTRootView源码,RCTRootView是UIView的子类,并且很简单。其中有一个属性:
1 @property (nonatomic, strong, readonly) RCTBridge *bridge;
通读类RCTBridge的代码,只有很少的200~300行。但是发现类RCTBatchedBridge继承自类RCTBridge。
类RCTBatchedBridge是Bridge模块的一个私有类,只被在类RCTBridge中被使用。这样设计使得接口和繁复的实现
分离。
TODO: Rewrite this section to match the modification in version 0.18.1
观察类 RCTCxxBridge.mm中的initiailizer,发现对接口的'initJS'的调用。在这里终于和JS '发生关系'。
- (instancetype)initWithParentBridge:(RCTBridge *)bridge
{
RCTAssertParam(bridge);
if ((self = [super initWithDelegate:bridge.delegate
bundleURL:bridge.bundleURL
moduleProvider:bridge.moduleProvider
launchOptions:bridge.launchOptions])) {
_parentBridge = bridge;
_performanceLogger = [bridge performanceLogger];
registerPerformanceLoggerHooks(_performanceLogger);
RCTLogInfo(@"Initializing %@ (parent: %@, executor: %@)", self, bridge, [self executorClass]);
/**
* Set Initial State
*/
_valid = YES;
_loading = YES;
_moduleRegistryCreated = NO;
_pendingCalls = [NSMutableArray new];
_displayLink = [RCTDisplayLink new];
_moduleDataByName = [NSMutableDictionary new];
_moduleClassesByID = [NSMutableArray new];
_moduleDataByID = [NSMutableArray new];
[RCTBridge setCurrentBridge:self];
}
return self;
}
在查看initJS方法的代码之前,我们先来关注比较重要的方法 registerModules。
Module 在React Native中实际上是 可以被 JavaScript 代码调用的模块, 实现了接口RCTBridgeModule的类。
Module 包含有 Native类型, JavaScript源码类型。
A): Native类型:
由Objective-C来实现相应的功能,并将接口提供给JavaScript代码调用。
B): JavaScript源码类型:
也就是用JavaScript写的React Native App。这个类型的Module由 RCTSourceCode类 来代表。
TODO: Rewrite this section to match the modification in version 0.18.1
1 - (void)registerModules
2 {
3 RCTAssertMainThread();
4
5 // Register passed-in module instances
6 NSMutableDictionary *preregisteredModules = [[NSMutableDictionary alloc] init];
7 for (id<RCTBridgeModule> module in self.moduleProvider ? self.moduleProvider() : nil) { // A
8 preregisteredModules[RCTBridgeModuleNameForClass([module class])] = module;
9 }
10
11 // Instantiate modules
12 _moduleDataByID = [[NSMutableArray alloc] init];
13 NSMutableDictionary *modulesByName = [preregisteredModules mutableCopy];
14 for (Class moduleClass in RCTGetModuleClasses()) { // B
15 NSString *moduleName = RCTBridgeModuleNameForClass(moduleClass);
16
17 // Check if module instance has already been registered for this name
18 id<RCTBridgeModule> module = modulesByName[moduleName];
19
20 if (module) {
21 // Preregistered instances takes precedence, no questions asked
22 if (!preregisteredModules[moduleName]) {
23 // It's OK to have a name collision as long as the second instance is nil
24 RCTAssert([[moduleClass alloc] init] == nil,
25 @"Attempted to register RCTBridgeModule class %@ for the name "
26 "'%@', but name was already registered by class %@", moduleClass,
27 moduleName, [modulesByName[moduleName] class]);
28 }
29 if ([module class] != moduleClass) {
30 RCTLogInfo(@"RCTBridgeModule of class %@ with name '%@' was encountered "
31 "in the project, but name was already registered by class %@."
32 "That's fine if it's intentional - just letting you know.",
33 moduleClass, moduleName, [modulesByName[moduleName] class]);
34 }
35 } else {
36 // Module name hasn't been used before, so go ahead and instantiate
37 module = [[moduleClass alloc] init];
38 }
39 if (module) {
40 modulesByName[moduleName] = module;
41 }
42 }
43
44 // Store modules
45 _modulesByName = [[RCTModuleMap alloc] initWithDictionary:modulesByName];
46
47 /**
48 * The executor is a bridge module, wait for it to be created and set it before
49 * any other module has access to the bridge
50 */
51 _javaScriptExecutor = _modulesByName[RCTBridgeModuleNameForClass(self.executorClass)]; // C
52 RCTLatestExecutor = _javaScriptExecutor;
53
54 [_javaScriptExecutor setUp];
55
56 // Set bridge
57 for (id<RCTBridgeModule> module in _modulesByName.allValues) { // D
58 if ([module respondsToSelector:@selector(setBridge:)]) {
59 module.bridge = self;
60 }
61
62 RCTModuleData *moduleData = [[RCTModuleData alloc] initWithExecutor:_javaScriptExecutor
63 uid:@(_moduleDataByID.count)
64 instance:module];
65 [_moduleDataByID addObject:moduleData];
66
67 if ([module conformsToProtocol:@protocol(RCTFrameUpdateObserver)]) {
68 [_frameUpdateObservers addObject:moduleData];
69 }
70 }
71 // E
72 [[NSNotificationCenter defaultCenter] postNotificationName:RCTDidCreateNativeModules
73 object:self];
74 }
A): A部分用来注册外部传递进来的Module。由于RCTBridge创建RCTBatchedBridge对象时,传入的参数导致
属性 self.moduleProvider 的值为nil,故我们先跳过这部分,直接跳到B部分。
B): B部分的循环是将加载的ModuleClass进行注册,注册到成员变量 '_modulesByName'中。
(其中的 RCTGetModuleClasses()和 RCTBridgeModuleNameForClass()
参见 iOS.ReactNative-3-about-viewmanager-uimanager-and-bridgemodule 中的说明)
C): 从'_modulesByName'中获取javaScriptExecutor,JS Executor是关键所在,JS Executor是执行JS代码的。
在 initJS 方法中会用到。
D): 为ModuleObject(模块对象/模块实例, 或者简称: 模块)设置bridge以及ModuleData(模块元数据),最后将实现接口RCTFrameUpdateObserver
的模块对象添加到'_frameUpdateObservers' 中。
E): 发送通知, NativeModules已创建完毕。TODO: 该通知的观察者做了哪些工作?
TODO: Rewrite this section to match the modification in version 0.18.1
- (void)initJS
{
RCTAssertMainThread();
// Inject module data into JS context
NSMutableDictionary *config = [[NSMutableDictionary alloc] init]; // A
for (RCTModuleData *moduleData in _moduleDataByID) {
config[moduleData.name] = moduleData.config;
}
NSString *configJSON = RCTJSONStringify(@{
@"remoteModuleConfig": config,
}, NULL);
[_javaScriptExecutor injectJSONText:configJSON
asGlobalObjectNamed:@"__fbBatchedBridgeConfig"
callback:^(NSError *error) {
if (error) {
[[RCTRedBox sharedInstance] showError:error];
}
}];
NSURL *bundleURL = _parentBridge.bundleURL;
if (_javaScriptExecutor == nil) {
/**
* HACK (tadeu): If it failed to connect to the debugger, set loading to NO
* so we can attempt to reload again.
*/
_loading = NO;
} else if (!bundleURL) {
// Allow testing without a script
dispatch_async(dispatch_get_main_queue(), ^{
_loading = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidLoadNotification
object:_parentBridge
userInfo:@{ @"bridge": self }];
});
} else { 40
RCTProfileBeginEvent();
RCTPerformanceLoggerStart(RCTPLScriptDownload);
RCTJavaScriptLoader *loader = [[RCTJavaScriptLoader alloc] initWithBridge:self]; // B
[loader loadBundleAtURL:bundleURL onComplete:^(NSError *error, NSString *script) {
RCTPerformanceLoggerEnd(RCTPLScriptDownload);
RCTProfileEndEvent(@"JavaScript download", @"init,download", @[]);
_loading = NO;
if (!self.isValid) {
return;
}
static BOOL shouldDismiss = NO;
if (shouldDismiss) {
[[RCTRedBox sharedInstance] dismiss];
}
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shouldDismiss = YES;
});
RCTSourceCode *sourceCodeModule = self.modules[RCTBridgeModuleNameForClass([RCTSourceCode class])];
sourceCodeModule.scriptURL = bundleURL;
sourceCodeModule.scriptText = script;
if (error) {
NSArray *stack = [error userInfo][@"stack"];
if (stack) {
[[RCTRedBox sharedInstance] showErrorMessage:[error localizedDescription]
withStack:stack];
} else {
[[RCTRedBox sharedInstance] showErrorMessage:[error localizedDescription]
withDetails:[error localizedFailureReason]];
}
NSDictionary *userInfo = @{@"bridge": self, @"error": error};
[[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidFailToLoadNotification
object:_parentBridge
userInfo:userInfo];
} else {
[self enqueueApplicationScript:script url:bundleURL onComplete:^(NSError *loadError) { // C
if (loadError) {
[[RCTRedBox sharedInstance] showError:loadError];
return;
}
/**
* Register the display link to start sending js calls after everything
* is setup
*/
NSRunLoop *targetRunLoop = [_javaScriptExecutor isKindOfClass:[RCTContextExecutor class]] ? [NSRunLoop currentRunLoop] : [NSRunLoop mainRunLoop];
[_jsDisplayLink addToRunLoop:targetRunLoop forMode:NSRunLoopCommonModes]; // D
// E
[[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidLoadNotification
object:_parentBridge
userInfo:@{ @"bridge": self }];
}];
}
}];
}
}
A): 将每个ModuleObject 元数据中的config 注册到 JS Executor中。(config 参见 5. RCTModuleData
B): 拉取JS Bundler, 可以将JS Bundler看作JS代码的'包'。
C): 执行Application JS code。(参见 4. JS Executor)
D): 将'_jsDisplayLink'添加到runloop中。'_jsDisplayLink'周期性的触发的工作是什么?
E): 发送通知 RCTJavaScriptDidLoadNotification。该通知的观察者进行了哪些处理?
到此,焦点会集中到JS Executor上面,接下来进行JS Executor的代码阅读。
TODO: Rewrite this section to match the modification in version 0.18.1
3.4.1 执行步骤
1: RCTBatchedBridge类的init方法中调用start方法来启动React Native App
- (instancetype)initWithParentBridge:(RCTBridge *)bridge
{
.......
[self start]; // 1
}
return self;
}
2: 在start方法的最后,模块初始化完毕,并且(React Native App的)源码加载完毕后执行源码。
模块的初始化包含两个部分:
A) JavaScript 模块的初始化
B) Native 模块的初始化。方法 initModules 完成了 Native模块的初始化。
1 - (void)start
2 {
3 ......
4 // Synchronously initialize all native modules that cannot be loaded lazily
5 [self initModules];
6
7 ......
8 dispatch_group_notify(initModulesAndLoadSource, dispatch_get_main_queue(), ^{
9 RCTBatchedBridge *strongSelf = weakSelf;
10 if (sourceCode && strongSelf.loading) {
11 dispatch_async(bridgeQueue, ^{
12 [weakSelf executeSourceCode:sourceCode]; // 2
13 });
14 }
15 });
3: executeSourceCode方法调用方法enqueueApplicationScript来执行(React Native App的)JavaScript源码。
- (void)executeSourceCode:(NSData *)sourceCode
{
......
RCTSourceCode *sourceCodeModule = [self moduleForClass:[RCTSourceCode class]];
sourceCodeModule.scriptURL = self.bundleURL;
sourceCodeModule.scriptData = sourceCode;
[self enqueueApplicationScript:sourceCode url:self.bundleURL onComplete:^(NSError *loadError) { // 3
......
// Register the display link to start sending js calls after everything is setup
NSRunLoop *targetRunLoop = [_javaScriptExecutor isKindOfClass:[RCTJSCExecutor class]] ? [NSRunLoop currentRunLoop] : [NSRunLoop mainRunLoop];
[_jsDisplayLink addToRunLoop:targetRunLoop forMode:NSRunLoopCommonModes];
// Perform the state update and notification on the main thread, so we can't run into
// timing issues with RCTRootView
dispatch_async(dispatch_get_main_queue(), ^{
[self didFinishLoading];
[[NSNotificationCenter defaultCenter]
postNotificationName:RCTJavaScriptDidLoadNotification
object:_parentBridge userInfo:@{@"bridge": self}];
});
}];
}
4: 方法enqueueApplicationScript 最终依赖RCTJSCExecutor类型的实例 _javaScriptExecutor
来执行(React Native App的)JavaScript源码。
1 - (void)enqueueApplicationScript:(NSData *)script
2 url:(NSURL *)url
3 onComplete:(RCTJavaScriptCompleteBlock)onComplete
4 {
5
6 [_javaScriptExecutor executeApplicationScript:script sourceURL:url onComplete:^(NSError *scriptLoadError) { // 4
7
8 .......
9
10 [_javaScriptExecutor flushedQueue:^(id json, NSError *error)
11 {
12
13 [self handleBuffer:json batchEnded:YES];
14
15 onComplete(error);
16 }];
17 }];
18 }
TODO: Rewrite this section to match the modification in version 0.18.1
接口RCTJavaScriptExecutor定义了JS Executor需要实现的接口。在React中提供了两个JS Executor的实现,
在React/Executors Group中:RCTWebViewExecutor、RCTContextExecutor。
WebSocket中也有一个实现: RCTWebSocketExecutor。
下面是接口RCTJavaScriptExecutor的方法声明:
typedef void (^RCTJavaScriptCompleteBlock)(NSError *error);
typedef void (^RCTJavaScriptCallback)(id json, NSError *error);
/**
* Abstracts away a JavaScript execution context - we may be running code in a
* web view (for debugging purposes), or may be running code in a `JSContext`.
*/
@protocol RCTJavaScriptExecutor <RCTInvalidating, RCTBridgeModule>
/**
* Used to set up the executor after the bridge has been fully initialized.
* Do any expensive setup in this method instead of `-init`.
*/
- (void)setUp;
/**
* Executes given method with arguments on JS thread and calls the given callback
* with JSValue and JSContext as a result of the JS module call.
*/
- (void)executeJSCall:(NSString *)name
method:(NSString *)method
arguments:(NSArray *)arguments
callback:(RCTJavaScriptCallback)onComplete;
/**
* Runs an application script, and notifies of the script load being complete via `onComplete`.
*/
- (void)executeApplicationScript:(NSString *)script
sourceURL:(NSURL *)sourceURL
onComplete:(RCTJavaScriptCompleteBlock)onComplete;
// 将由script表示的JavaScript脚本代表的object以objectName注册为全局变量。
- (void)injectJSONText:(NSString *)script
asGlobalObjectNamed:(NSString *)objectName
callback:(RCTJavaScriptCompleteBlock)onComplete;
/**
* Enqueue a block to run in the executors JS thread. Fallback to `dispatch_async`
* on the main queue if the executor doesn't own a thread.
*/
- (void)executeBlockOnJavaScriptQueue:(dispatch_block_t)block;
@optional
/**
* Special case for Timers + ContextExecutor - instead of the default
* if jsthread then call else dispatch call on jsthread
* ensure the call is made async on the jsthread
*/
- (void)executeAsyncBlockOnJavaScriptQueue:(dispatch_block_t)block;
@end
RCTJSCExecutor实现了接口RCTJavaScriptExecutor:
1 /**
2 * Uses a JavaScriptCore context as the execution engine.
3 */
4 @interface RCTJSCExecutor : NSObject <RCTJavaScriptExecutor>
5. RCTModuleData
RCTModuleData实例保存关于RCTBridgeModule实例的数据,这些数据包含: "bridge module"模块的类(1),
"bridge module"模块在Javascript中名字(2), "bridge module"模块导出到JavaScript中的 Method(3),
"bridge module"模块实例(4), the module method dispatch queue(5), "bridge module"模块的配置信息(6)。
@property (nonatomic, strong, readonly) Class moduleClass; // 1
@property (nonatomic, copy, readonly) NSString *name; // 2
@property (nonatomic, copy, readonly) NSArray<id<RCTBridgeMethod>> *methods; // 3
@property (nonatomic, strong, readonly) id<RCTBridgeModule> instance; // 4
@property (nonatomic, strong, readonly) dispatch_queue_t methodQueue; // 5
@property (nonatomic, copy, readonly) NSArray *config; // 6
RCTModuleData的方法instance 会创建"bridge module"模块实例:
- (id<RCTBridgeModule>)instance
{
[_instanceLock lock];
if (!_setupComplete) {
if (!_instance) {
_instance = [_moduleClass new];
}
// Bridge must be set before methodQueue is set up, as methodQueue
// initialization requires it (View Managers get their queue by calling
// self.bridge.uiManager.methodQueue)
[self setBridgeForInstance];
[self setUpMethodQueue];
[_bridge registerModuleForFrameUpdates:_instance withModuleData:self];
_setupComplete = YES;
}
[_instanceLock unlock];
return _instance;
}
从本地文件系统或者远程Server加载JavaScript。
+ (void)loadBundleAtURL:(NSURL *)scriptURL onComplete:(RCTSourceLoadBlock)onComplete
该接口实现使用了 NSURLSessionDataTask, React Native需要 iOS 7.0+ 的系统。
RCTSourceCode抽象JavaScript源码数据, 包含属性:
scriptData 和 scriptURL
@interface RCTSourceCode : NSObject <RCTBridgeModule> // E
@property (nonatomic, copy) NSData *scriptData;
@property (nonatomic, copy) NSURL *scriptURL;
@end
本文mark下,重要的是思路,以备后面用的着就转载过来了,版本不一样,了,有些对不上了,可是思路还是那个