How to convert NSValue to NSData and back?

后端 未结 3 1319
旧巷少年郎
旧巷少年郎 2020-12-30 07:45

A have a number of NSValue (obtained via KVC valueForKey) that I need to append to an NSData object in order to send it over the netwo

3条回答
  •  -上瘾入骨i
    2020-12-30 08:27

    Martin Gordon's answer is getting close, but fortunately you don't have to manually parse the objCType string. There's a function that does that: NSGetSizeAndAlignment. From that you get the size/length of the value obtained from getValue:. This question lead me to the solution.

    I ended up creating a category for NSData that allows me to create NSData from NSNumber or NSValue objects:

    @interface NSData (GameKitCategory)
    +(NSData*) dataWithValue:(NSValue*)value;
    +(NSData*) dataWithNumber:(NSNumber*)number;
    @end
    
    @implementation NSData (GameKitCategory)
    +(NSData*) dataWithValue:(NSValue*)value
    {
        NSUInteger size;
        const char* encoding = [value objCType];
        NSGetSizeAndAlignment(encoding, &size, NULL);
    
        void* ptr = malloc(size);
        [value getValue:ptr];
        NSData* data = [NSData dataWithBytes:ptr length:size];
        free(ptr);
    
        return data;
    }
    
    +(NSData*) dataWithNumber:(NSNumber*)number
    {
        return [NSData dataWithValue:(NSValue*)number];
    }
    @end
    

    I also add a small header before this NSValue/NSNumber data that allows me to decode which property the data is for and how many bytes are in the data section. With that I can restore the value to the remote property.

提交回复
热议问题