IOS低水平系列化

问题描述:

下面是一个Java / Android的功能:

Here is a Java / Android function:

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的做太多。或者,我想还是找不到一个低级的数据结构/类中使用的。

I would like to do at iOS too. Or I miss or can't find a low level data structure / class what to use.

NSData的和 NSMutableData ​​A>算得上是一个对象,它封装了一个字节数组,但他们有效功能只在 dataContentsOfFile 和将writeToFile 。

NSData and NSMutableData claim to be an object which wraps a byte array, but they usefully function is only the dataContentsOfFile and writeToFile.

NSArchiver 是像一个ObjectOutputStream。

NSArchiver is like an ObjectOutputStream.

档案和序列化编程指南
无法找到这把关键例如en codeBytes不需要任何方法:长:forKey:

Archives and Serializations Programming Guide Can't find any method which not required to put a key like encodeBytes:length:forKey:

我不希望推倒重来,也不能挽救使用了很多不必要的数据。

I don't want to reinvent the wheel, nor use a lot of unnecessary data at saving.

是具有putLong()putFloat()putInt(任何工具类),并char或字节数组正确?

Is any utility class which has a putLong() putFloat() putInt() and make a char or byte array properly?

我发现the同样的问题以及这个答案是基于它。您可以轻松地创建一个实现使用相同的接口的ByteBuffer NSOutputStream 。事情是这样的:结果

I've found the same question and this answer is based on it. You can easily create a class that implements the same interface as ByteBuffer using NSOutputStream. Something like this:

- (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];
}