【发布时间】:2013-09-06 11:11:46
【问题描述】:
这是一个 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 数组?
【问题讨论】:
-
嗯,你试试 NSCache 吗? [NSCache 示例][1] [1]:stackoverflow.com/questions/12817476/…
-
@daro2189 比 NSMutableDictionary 差一点
标签: android ios optimization serialization