本文介绍了如何将NSNumber转换为NSData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 sendDataToAllPeers传输通过的GameKit整数:withDataMode:错误:,但我不知道怎么我的NSNumber转换为NSData的才能发送。我目前有:

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];

但很明显,在我发送之前,indexNum需要转换为NSData。有谁知道怎么做?

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

谢谢!

推荐答案

对于这样一个简单的任务,我不推荐 NSKeyedArchiver ,因为它会在它上面添加PLIST开销和类版本。

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

包装:

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

发送:

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

解包(在GKSession接收处理程序中):

Unpack (in the GKSession receive handler):

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



Swift



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"

这篇关于如何将NSNumber转换为NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:28