1

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

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 and NSMutableData claim to be an object which wraps a byte array, but they usefully function is only the dataContentsOfFile and writeToFile.

NSArchiver is like an ObjectOutputStream.

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.

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

1 Answers1

1

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];
}
Community
  • 1
  • 1
Ilia
  • 1,434
  • 15
  • 22
  • +1 thank you, I will check at office the code and probably it will be accepted the answer too –  Sep 06 '13 at 17:28