您的位置:首页 > 其它

添加 struct 类型支持

2016-03-03 13:27 225 查看
JSPatch 默认支持的 struct 类型只有 CGRect / CGPoint / CGSize / NSRange,若要让 JS 脚本支持其他
struct 类型,需要先手动注册。例如要支持 CGAffineTransform,需要在使用前在 JS 使用 
defineStruct()
 接口定义:

require('JPEngine').defineStruct({
"name": "CGAffineTransform",
"types": "FFFFFF",
"keys": ["a", "b", "c", "d", "tx", "ty"]
})


API

JPEngine
 的 
+defineStruct:
 接口,可以让
JS 支持新的 struct 类型:

@interface JPEngine : NSObject
/*
@param defineDict = @{
@"name": @"",   //struct 名
@"types": @"",  //struct 各字段类型
@"keys": @[@"", ...]  //struct 各字段名
}
*/
+ (void)defineStruct:(NSDictionary *)defineDict;
...
@end


types

types 字段表示 struct 各字段的类型,每种类型都由一个字母代替,字母含义如下:

'c': char
'C': unsigned char
's': short
'S': unsigned short
'i': int
'I': unsigned int
'l': long
'L': unsigned long
'q': long long
'Q': unsigned long long
'f': float
'F': CGFloat
'N': NSInteger
'U': NSUInteger
'd': double
'B': BOOL

这里 struct 有多少个字段,types 就有多少个字母,types 的字母顺序必须按 struct 定义的顺序写,举例:

struct JPDemoStruct {
CGFloat a;
long b;
double c;
BOOL d;
}

JPDemoStruct
 对应的
type 就是 
@"FldB"



keys

keys 数组表示 struct 各个字段在 JS 中使用的名字,其顺序必须与 struct 字段顺序一致,拿上述 
JPDemoStruct
 举例,它对应的
keys 数组应该是:
@[@"a", @"b", @"c", @"d"]
.


完整例子

OC 里有 
JPDemoStruct
 这个 struct 类型:

struct JPDemoStruct {
CGFloat a;
long b;
double c;
BOOL d;
}


想在 JS 上使用,需要事先调用定义:

[JPEngine defineStruct:@{
@"name": @"JPDemoStruct",
@"types": @"FldB",
@"keys": @[@"a", @"b", @"c", @"d"]
}]


接着就可以在 JS 里使用了:

//OC
@implementation JPObject
+ (void)passStruct:(JPDemoStruct)s;
+ (JPDemoStruct)returnStruct;
@end


//JS
require('JPObject').passStruct({a:1, b:2, c:4.2, d:1})
var s = require('JPObject').returnStruct();



动态定义

我们也可以在 JS 里动态定义 struct 类型:

require('JPEngine').defineStruct({
"name": "JPDemoStruct",
"types": "FldB",
"keys": ["a", "b", "c", "d"]
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: