arrays - NSString 到数组整数 Swift Xcode

标签 arrays swift nsstring xcode6

我正在使用 Multipeer Connectivity 在 Swift 中制作一个程序,以在设备之间发送信息。我正在发送一个包含整数的数组,我需要将其转换为 NSDictionary,但是当我试图将其恢复为整数数组时,我无法设法将其恢复。我知道这是一种将 NSString 转换为 Integer 的方法,请参阅 here ,但我找不到数组的方法。有谁知道我该怎么做?

我在发送信息的节点中的代码如下所示:

let numberArray:[Int] = [4,76,23,65,23,75,23,65,12]

let messageDict = ["newNumbersArray":numberArray]        
let messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

var error:NSError?

appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: &error)

在另一个节点中,我的代码如下所示:

func handleReceivedDataWithNotification(notification:NSNotification){
    let userInfo = notification.userInfo! as Dictionary
    let receivedData:NSData = userInfo["data"] as NSData

    let message = NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
}

如何将它转换回带有 int 的数组?

最佳答案

在不同系统之间“在线”发送信息有两种主要方法:第一种称为序列化,第二种称为编码(marshal)处理。

序列化:

信息按照约定编码为有线格式。在现代 Cocoa 中,最常见的序列化类型是 plist 和 JSON。

编码:

编码(marshal)处理类似于序列化,不同之处在于它允许使用映射文件覆盖默认行为。这对于契约优先开发非常有用,其目的是尽量保持信息格式在超时时尽可能稳定,即使系统内部可能会改变结构。否则,一项更改将意味着服务的所有订阅者也需要更改。

还有一种非正式的方法,就像您正在做的那样。但是为什么不尝试使用以下方法将您的字典序列化为有线格式:

let dictionary : Dictionary = ["newNumbersArray":numberArray]   
let data = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)


然后从另一个节点的 JSON 返回:

var dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as Dictionary


否则,如果您想继续使用非正式的序列化方法,您只需遍历集合中的每个项目,将其从字符串转换为整数,然后将结果添加到另一个数组。 Underscore.m库提供了一个映射函数,这样你就可以用更少的代码来做到这一点。

关于arrays - NSString 到数组整数 Swift Xcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943203/

相关文章:

ios - 如何限制 UITextView iOS 中的字符

C 指针和数组

java - PHP中数组概念的澄清

swift - 解析 Facebook 登录错误 - Swift 2

ios - Xcode Beta 6 上的 NSString 和 String

iphone - 字符串中的 Unicode 字符 - iphone

javascript - 如何将此类对象的此类数组传递给 JS?

c++ - 查找两个数组的交集

ios - Alamofire - 多部分表单数据 key :value

ios - 找不到 Project-Swift.h 文件