How to convert NSValue to NSData and back?

后端 未结 3 1328
旧巷少年郎
旧巷少年郎 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条回答
  •  感动是毒
    2020-12-30 08:35

    Since NSValue adopts the NSCoding protocol, you can use the NSCoder subclasses, NSKeyedArchiver and NSKeyedUnarchiver:

    - (NSData *)dataWithValue:(NSValue *)value {
      return [NSKeyedArchiver archivedDataWithRootObject:value];
    }
    
    - (NSValue *)valueWithData:(NSData *)data {
      return (NSValue *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    

    If NSKeyedArchiver and NSKeyedUnarchiver can't be used (for resulting data size issues), then you would have to find the size of the contained value yourself:

    - (NSData *)dataWithValue:(NSValue *)value {
      // Can use NSGetSizeAndAlignment() instead. See LearnCocos2D's answer.
      if (type[0] == '{') {
        // Use the various NSValue struct value methods to detect the type.
      } else if (type[0] == 'c') {
        size = sizeof(char);
      } else if (type[0] == 'i') {
        size = sizeof(int);     
      } // etc for all/most of the values in the table linked below [1];
    
      void *bytes = malloc(size);
      [value getValue:bytes];
      return [NSData dataWithBytes:bytes length:size];
    }
    

    [1]: Objective-C Type Encodings

提交回复
热议问题