How to encode / decode CFUUIDRef in Objective-C

I want to have a GUID in my objective-c model to act as a unique identifier. My problem is how to save CFUUIDRef with my NSCoder since it is not an object type.

I continue to play with the following lines for encoding / decoding, but I cannot find good examples of how to save structure types in objective-c (all my NSObject types are perfectly encoded / decoded).

eg. for coding I'm trying (which, I think, looks good?):

CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
eencoder encodeBytes: &bytes length: sizeof(bytes)];

and for decoding, where I get stuck more:

NSUInteger blockSize;
const void* bytes = [decoder decodeBytesForKey: kFieldCreatedKey returnedLength:&blockSize];
if(blockSize > 0) {
     uuid = CFUUIDCreateFromUUIDBytes(NULL, (CFUUIDBytes)bytes);
}

I gt "convert to non-scalable type" error above - I tried several implementations of the bits of code that I saw on the Internet. Can someone point me in the right direction? Tim

+3
3

( ) NSString (CFString), CFUUIDCreateString, UUID CFUUIDCreateFromString.

+2

- , "" - CFUUIDBytes, , CFUUIDBytes, . :

uuid = CFUUIDCreateFromUUIDBytes(NULL, *((CFUUIDBytes*)bytes));

, "" CFUUIDBytes ( ), ( ). , , .

+2

Based on the answers I received, I tried the casting approach proposed by Eyal, as well as the NSData approach proposed by Rob, and I thought the latter seemed clearer, although I am interested in what others think.

I got the following:

- (void)encodeWithCoder:(NSCoder *)encoder {  
    // other fields encoded here
    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
    NSData* data  = [NSData dataWithBytes: &bytes length: sizeof(bytes)];
    [encoder encodeObject: data forKey: kFieldUUIDKey];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) { 
        // other fields unencoded here
        NSData* data = [decoder decodeObjectForKey: kFieldUUIDKey];
        if(data) {
          CFUUIDBytes uuidBytes;
          [data getBytes: &uuidBytes];
          uuid = CFUUIDCreateFromUUIDBytes(NULL,uuidBytes);
    } else {
          uuid = CFUUIDCreate(NULL);
        }
    }
  }
0
source

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


All Articles