KryoCocoa

作者: joshuafei | 来源:发表于2016-08-29 15:32 被阅读0次

    什么是Kryo

    Kryo 是一个快速高效的Java对象图形序列化框架,主要特点是性能、高效和易用。该项目用来序列化对象到文件、数据库或者网络。

    http://code.google.com/p/kryo

    Kryo同其他序列化框架的对比(Java比较流行的序列化框架)

    Kryo, 优点:速度快,序列化后体积小;缺点:跨语言支持较复杂

    Hessian,优点:默认支持跨语言;缺点:较慢

    Protostuff ,优点:速度快,基于protobuf;缺点:需静态编译

    什么是KryoCocoa

    其实KryoCocoa就是Java中Kryo序列化框架的Objective-C版,是为了兼容Kryo和基本的Java数据类型的。

    这里是KryoCocoa的地址:https://github.com/Feuerwerk/kryococoa

    基本使用

    一、将对象序列化后写入某个文件中

    假如有以下实体类:

    @interfaceClassA:NSObject@property(assign,nonatomic) SInt32 uid;@property(copy,nonatomic)NSString*name;@end

    将该实体类序列化后写入到某个路径下的某个文件

    ClassA *a = [[ClassA alloc] init];

    a.uid=1;

    a.name=@"lisi";NSOutputStream*outputStream = [NSOutputStreamoutputStreamToFileAtPath:filePath append:NO];

    KryoOutput *output = [[KryoOutput alloc] initWithStream:outputStream];

    [k writeObject:a to:output];

    [output close];

    二、读取某个文件反序列化成一个对象

    NSInputStream*inputStream = [NSInputStreaminputStreamWithFileAtPath:filePath];

    KryoInput *input = [[KryoInput alloc] initWithInput:inputStream];

    ClassA *a = [k readObject:input ofClass:[ClassA class]];

    [input close];NSLog(@"%d %@", a.uid,a.name);

    序列化对象后通过Socket与Java后台交互

    假设有一个这样的java实体类

    packagecom.test.web.socket.modules.user.svo;publicclassTestSVO{privateLong uid;privateInteger status;publicLonggetUid(){returnuid;

    }publicvoidsetUid(Long uid){this.uid = uid;

    }publicIntegergetStatus(){returnstatus;

    }publicvoidsetStatus(Integer status){this.status = status;

    }

    }

    我们在Xcode中应该这样定义

    #import#import"SerializationAnnotation.h"#import"JInteger.h"#import"JLong.h"@interfaceTestSVO:NSObject// 更多OC对应java类型可在git上面查到,不一一列举了@property(strong,nonatomic) JLong *uid;@property(strong,nonatomic) JInteger *status;@end

    #import"TestSVO.h"@implementationTestSVO+ (NSString*)serializingAlias

    {//这里返回的java中的完整报名+类名,否则会出问题return@"com.test.web.socket.modules.user.svo.TestSVO";

    }@end

    假设我们要将上面的对象通过socket发送给服务器

    Kryo *k = [Kryo new];// 创建一个内存输出流 用于输出Kryo序列化后的东西NSOutputStream*outputStream = [[NSOutputStreamalloc] initToMemory];// KryoOutput这个类实际上就是NSOutputStream的子类KryoOutput *output = [[KryoOutput alloc] initWithStream:outputStream];

    [k writeObject:message to:output];// toData获取到NSDataNSData*contents = output.toData;intlen = (int)contents.length;// 发送数据NSData*lengthData = [NSDatadataWithBytes:&len length:sizeof(len)];

    [self.socketwriteData:[selfdescBytesWithNSData:lengthData] withTimeout:WRITE_TIME_OUT tag:0];

    [self.socketwriteData:contents withTimeout:WRITE_TIME_OUT tag:0];

    [output close];

    这样子,Kryo的基本使用就告一段落了。

    转载自:http://www.zhiyingme.com/a/xinwenzixun/mingjiaguandian/60.html

    相关文章

      网友评论

          本文标题:KryoCocoa

          本文链接:https://www.haomeiwen.com/subject/mngxettx.html