IOS low-level serialization

Here is the 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 also like to do in iOS. Either I am missing or cannot find the low level data structure / class what to use.

NSData and NSMutableData claim to be an object that wraps an array of bytes, but they are only useful for dataContentsOfFile and writeToFile .

NSArchiver is like an ObjectOutputStream.

Programming and Serialization Guide Cannot find any method that is not required to enter a key of type encodeBytes: length: forKey:

I do not want to reinvent the wheel and not use a lot of extra data when saving.

- , putLong() putFloat() putInt() char ?

+1
1

, . , , ByteBuffer, NSOutputStream. - :

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

Source: https://habr.com/ru/post/1705273/


All Articles