KryoCocoa

来源:互联网 发布:linux apache ssl下载 编辑:程序博客网 时间:2024/05/16 06:25

什么是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) NSStringname;@end将该实体类序列化后写入到某个路径下的某个文件ClassA a = [[ClassAalloc] init];a.uid = 1;a.name = @"lisi";

NSOutputStream outputStream =[NSOutputStream outputStreamToFileAtPath:filePath append:NO];KryoOutputoutput= [[KryoOutput alloc] initWithStream:outputStream];[k writeObject:a to:output];

[output close];
二、读取某个文件反序列化成一个对象NSInputStream inputStream =[NSInputStream inputStreamWithFileAtPath:filePath];KryoInputinput =[[KryoInput alloc] initWithInput:inputStream];ClassA *a = [k readObject:inputofClass:[ClassA class]];

[input close];NSLog(@"%d%@", a.uid,a.name);序列化对象后通过Socket与Java后台交互假设有一个这样的java实体类packagecom.test.web.socket.modules.user.svo;

public class TestSVO {

private Long uid;private Integer status;public Long getUid(){ return uid;}public void setUid(Long uid) { this.uid = uid;}public IntegergetStatus() { return status;}public void setStatus(Integer status) {this.status = status;}

}我们在Xcode中应该这样定义

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

@property (strong, nonatomic)JInteger *status;

@end

import "TestSVO.h"@implementation TestSVO

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

@end假设我们要将上面的对象通过socket发送给服务器Kryok = [Kryo new];// 创建一个内存输出流 用于输出Kryo序列化后的东西NSOutputStreamoutputStream= [[NSOutputStream alloc] initToMemory];// KryoOutput这个类实际上就是NSOutputStream的子类KryoOutput*output = [[KryoOutput alloc] initWithStream:outputStream];

[k writeObject:message to:output];// toData获取到NSDataNSData *contents =output.toData;int len = (int)contents.length;// 发送数据NSData *lengthData = [NSDatadataWithBytes:&len length:sizeof(len)];[self.socket writeData:[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

 

0 0
原创粉丝点击