这是一个Java / Android功能:
public static byte[] serialize(MyClass myObject) {
int byteArraySizeNeeded = getByteArraySizeNeededForSerialize(myObject);
byte[] result = new byte[byteArraySizeNeeded];
ByteBuffer bb = ByteBuffer.wrap(result);
bb.putShort((short) (byteArraySizeNeeded-2));// 2 - not need to read at deserialisation!
bb.putLong(myObject.getProperty1ValueWhichIsALong());// 8
bb.putDouble(myObject.getProperty2ValueWhichIsADouble());// 8
bb.putFloat(myObject.getProperty3ValueWhichIsAFloat);//4
bb.put(CODE_MYCODE1); // code
bb.putFloat(myObject.getProperty4ValueWhichIsAFloat);
// there are a lot of properties and the list is dynamic: some need to be saved some not: eg if property 10 exists than not needed to save property 11 and property 25 is saved only if not null and so on.
int curPosition = bb.position();
int offset = 2; // skip the first 2 bytes representing the size of byte buffer needed to allocate.
int byteCount = curPosition - offset;
myObject.crc.update(result, offset, byteCount);
long crcValue = myObject.crc.getValue();
bb.put(CODE_CRC); // code
bb.putLong(crcValue);// only distinct data values
return result;
}
我也想在iOS上做。或者我想念或找不到低级数据结构/类使用什么。
NSData和NSMutableData声称是一个包装字节数组的对象,但它们有用的功能只有dataContentsOfFile和writeToFile。
NSArchiver就像一个ObjectOutputStream。
Archives and Serializations Programming Guide 找不到任何不需要输入像encodeBytes这样的密钥的方法:length:forKey:
我不想重新发明轮子,也不想在保存时使用大量不必要的数据。
是否有任何实用程序类具有putLong()putFloat()putInt()并正确生成char或byte数组?
答案 0 :(得分:1)
我找到了the same question,这个答案是基于它的。您可以使用NSOutputStream轻松创建一个与ByteBuffer实现相同接口的类。这样的事情:
- (NSOutputStream*)outputStream {
if (_outputStream == nil) {
_outputStream = [[NSOutputStream alloc] initToMemory];
[_outputStream open];
}
return _outputStream;
}
- (void)putInt:(NSInteger)value {
[self.outputStream write:(uint8_t*)&value maxLength:sizeof(NSInteger)];
}
- (NSData*)data {
return [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
}