How do I convert an NSNumber to NSData?

18,954

Solution 1

I would not recommend NSKeyedArchiver for such a simple task, because it adds PLIST overhead on top of it and class versioning.

Pack:

NSUInteger index = <some number>;
NSData *payload = [NSData dataWithBytes:&index length:sizeof(index)];

Send:

[session sendDataToAllPeers:payload withDataMode:GKSendDataReliable error:nil];

Unpack (in the GKSession receive handler):

NSUInteger index;
[payload getBytes:&index length:sizeof(index)];

Swift

var i = 123
let data = NSData(bytes: &i, length: sizeof(i.dynamicType))

var i2 = 0
data.getBytes(&i2, length: sizeof(i2.dynamicType))

print(i2) // "123"

Solution 2

To store it:

NSData *numberAsData = [NSKeyedArchiver archivedDataWithRootObject:indexNum];

To convert it back to NSNumber:

NSNumber *indexNum = [NSKeyedUnarchiver unarchiveObjectWithData:numberAsData]; 

Solution 3

Why not send the integer directly like this:

NSData * indexData = [NSData dataWithBytes:&index length:sizeof(index)];
[gkSession sendDataToAllPeers:indexData withDataMode:GKSendDataReliable error:nil];
Share:
18,954

Related videos on Youtube

jowie
Author by

jowie

Bedroom/pub/club DJ, biker, programmer, musician and general all-round great guy ;-)

Updated on May 05, 2022

Comments

  • jowie
    jowie about 2 years

    I need to transmit an integer through GameKit using sendDataToAllPeers:withDataMode:error: but I don't know how to convert my NSNumber to NSData in order to send. I currently have:

    NSNumber *indexNum = [NSNumber numberWithInt:index];
    [gkSession sendDataToAllPeers:indexNum withDataMode:GKSendDataReliable error:nil];
    

    but obviously the indexNum needs to be converted to NSData before I can send it. Does anyone know how to do this please?

    Thanks!

  • Raj Pawan Gumdal
    Raj Pawan Gumdal over 11 years
    You assume that the number is a NSUInteger while unpacking. NSNumber can wrap whole lot of different type of numbers - int, float, double, signed / unsigned. I think that archiving and unarchiving is best approach if programmer is not sure what type of data is stored in NSNumber. I go with Ole's approach.
  • Era
    Era over 11 years
    Where do you see NSNumber? I never use NSNumber.
  • Raj Pawan Gumdal
    Raj Pawan Gumdal over 11 years
    The question asked was for NSNumber created from an integer. So, I guess a general solution for NSNumber would have been more appropriate.
  • Sifeng
    Sifeng over 9 years
    @Erik Aigner: do you know how to solve this problem with Swift? Thanks in advance!