【问题标题】:Is it possible to save NSData(obtained from NSKeyedArchiver) as NSString and then read back as NSData?是否可以将 NSData(从 NSKeyedArchiver 获得)保存为 NSString,然后作为 NSData 读回?
【发布时间】:2018-01-04 21:25:07
【问题描述】:

我想将一些信息保存到视频元数据中。现在我可以保存文本,即String 对象。

// this works well
let metaItem = AVMutableMetadataItem()
metaItem.key = AVMetadataCommonKeySource as NSCopying & NSObjectProtocol
metaItem.keySpace = AVMetadataKeySpaceCommon
metaItem.value = String("some text") as! NSCopying & NSObjectProtocol

所以我想序列化自定义对象,而不仅仅是String

class ARTRMetadata: NSObject, NSCoding {
   // ... 
   required init(coder aDecoder: NSCoder) {
        //...
   }
   func encode(with aCoder: NSCoder) {
        //...
   }
}

我尝试将Data 转换为String,它崩溃了,现在我坚持将Data 写入/读取.txt 文件:

static func saveMetadataObjectAsText(memento: ARTRMetadata)->String {
        let tempFilepath = NSTemporaryDirectory().appending("someFile2.txt")
        FileManager.default.createFile(atPath: tempFilepath, contents: nil, attributes: nil)

        if NSKeyedArchiver.archiveRootObject(memento, toFile: tempFilepath) {}
        else { print("archiveRootObject toFile: FAILURE") }

        do {
           let contentsFeedToMetadataItem = try String(contentsOfFile: tempFilepath)
           //let contentsFeedToMetadataItem = try String(contentsOfFile: tempFilepath, encoding: String.Encoding.utf8) // The file “someFile2.txt” couldn’t be opened using text encoding Unicode (UTF-8).
           return contentsFeedToMetadataItem
        }
        catch { print(error) }
        return "ERROR in contentsFeedToMetadataItem"
    }

现在它崩溃了,因为“无法打开文件“someFile2.txt”,因为无法确定其内容的文本编码。”

我想问题是从NSKeyedArchiver 获得的NSData 是无效的NSString。如果我是正确的,如何将数据转储为文本?然后用相同的字节恢复它(NSKeyedUnarchiver)?

提前致谢!

【问题讨论】:

    标签: swift nsstring nsdata nskeyedarchiver


    【解决方案1】:

    为什么要将数据保存为文本文件?即使您可以将Data 保存为字符串(如果您使用base64 对其进行编码,确实可以),它仍然不是人类可读的——可能很少有人可以流利地阅读base64。

    长话短说,将Data 直接保存到磁盘并读回。 Data 提供相应的 API。

    顺便说一句:archiveRootObject(toFile 无论如何都会写 Data,所以请阅读 try Data(contentsOfFile: tempFilepath) 并返回它。

    【讨论】:

    • 非常感谢!我会在星期一检查它,然后接受。 :)
    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多