문제
JavaScriptCore 프레임 워크는 JavaScript 객체를 objective-c 객체로 어떻게 변환합니까?브리지는 동일한 바이너리 프로토콜을 사용하여 두 가지 대상 언어 모두를 위해 통신합니까?
해결책
iOS7에서 소개 된 Objective-C 프레임 워크는 모든 무거운 리프팅을 수행합니다. 객체를 동일한 바이너리로 생각할 필요가 없지만 다르게 해석됩니다. objc와 자바 스크립트를 변환 할 때 복사본 을 수행합니다.
jsvalue.h :
// Conversion between Objective-C and JavaScript types.
//
// When converting between JavaScript values and Objective-C objects a copy is
// performed. Values of types listed below are copied to the corresponding
// types on conversion in each direction. For NSDictionaries, entries in the
// dictionary that are keyed by strings are copied onto a JavaScript object.
// For dictionaries and arrays, conversion is recursive, with the same object
// conversion being applied to all entries in the collection.
Objective-C type | JavaScript type
--------------------+---------------------
nil | undefined
NSNull | null
NSString | string
NSNumber | number, boolean
NSDictionary | Object object
NSArray | Array object
NSDate | Date object
NSBlock * | Function object *
id ** | Wrapper object **
Class *** | Constructor object ***
* Instances of NSBlock with supported arguments types will be presented to
JavaScript as a callable Function object. For more information on supported
argument types see JSExport.h. If a JavaScript Function originating from an
Objective-C block is converted back to an Objective-C object the block will
be returned. All other JavaScript functions will be converted in the same
manner as a JavaScript object of type Object.
** For Objective-C instances that do not derive from the set of types listed
above, a wrapper object to provide a retaining handle to the Objective-C
instance from JavaScript. For more information on these wrapper objects, see
JSExport.h. When a JavaScript wrapper object is converted back to Objective-C
the Objective-C instance being retained by the wrapper is returned.
*** For Objective-C Class objects a constructor object containing exported
class methods will be returned. See JSExport.h for more information on
constructor objects.
.
(간단한 유형의 경우) :
NSString *myString = [javascriptContext[@"myJSVar"] toString];
.
및
javascriptContext[@"myJSVar"] = myString;
.
또는보다 복잡한 객체의 경우 jsexport 프로토콜을 사용하십시오.
@protocol MyPointExports <JSExport>
@property double x;
@property double y;
@end
@interface MyPoint : NSObject <MyPointExports>
// Put methods and properties not visible to JavaScript code here.
@end
...
javascriptContext[@"MyPoint"] = [MyPoint class]; // Define the class in Javascript
.
그런 다음
MyPoint *p = [javascriptContext[@"myJSPointVar"] toObject];
.
및
javascriptContext[@"myJSPointVar"] = p;
.
프로토콜에 선언 된 각 속성에 대해 프레임 워크는 JS getter / setter를 빌드하므로 JavaScript 내에서 다음을 수행 할 수 있습니다.
myJSPointVar.x = 10;
.
JavaScriptCore 프레임 워크의 소개를 찾는 독자의 경우 2013 WWDC 비디오 / PDF "Apple의 개발자 네트워크에서 Native Apps"세션에 JavaScript 통합 "을 확인하십시오.
다른 팁
이 클래스를 살펴보십시오. nsjsonserialization.
제휴하지 않습니다 StackOverflow