How do I convert an NSNumber to NSData?

前端 未结 4 635
鱼传尺愫
鱼传尺愫 2020-12-31 03:37

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 se

相关标签:
4条回答
  • 2020-12-31 04:21

    Why not send the integer directly like this:

    NSData * indexData = [NSData dataWithBytes:&index length:sizeof(index)];
    [gkSession sendDataToAllPeers:indexData withDataMode:GKSendDataReliable error:nil];
    
    0 讨论(0)
  • 2020-12-31 04:33

    To store it:

    NSData *numberAsData = [NSKeyedArchiver archivedDataWithRootObject:indexNum];
    

    To convert it back to NSNumber:

    NSNumber *indexNum = [NSKeyedUnarchiver unarchiveObjectWithData:numberAsData]; 
    
    0 讨论(0)
  • 2020-12-31 04:34

    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"
    
    0 讨论(0)
  • 2020-12-31 04:35

    For a more detailed example how to send different payloads you can check the GKRocket example included in the XCode documentation.

    0 讨论(0)
提交回复
热议问题