我将UIImages保存到磁盘:
let sketchData: NSData = UIImagePNGRepresentation(sketch)
let sketchPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents/Sketch\(indexNumber).png")
sketchData.writeToFile(sketchPath, atomically: true)
然后,我试图用它们重新填充数组:
if lengthOfSketchArray > 0 {
for indexNumber in 0...lengthOfSketchArray {
let sketchPath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents/Sketch\(indexNumber).png")
let image = UIImage(contentsOfFile: sketchPath)
slideSketchArray[indexNumber] = image!
}
}
在最后一行,我得到了#34;致命错误:在打开一个可选值"时意外地发现了nil。
我尝试了很多变化,但每个人都崩溃了。我做错了什么?
更新
它现在正在工作!我根据评论改变了很多东西,包括使用
NSSearchPathForDirectoriesInDomains
,以及不再在数组中保存图像。现在我保存图像路径,并在需要时从磁盘加载图像。
func saveImageToDisk() {
let sketchData: NSData = UIImagePNGRepresentation(sketch)
let destinationFolder: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let sketchPath: String = "\(destinationFolder)\(currentProjectID).png"
sketchData.writeToFile(sketchPath, atomically: true)
let currentMetadata: [String: String] = [
"sketchpath": sketchPath
]
allMetadata.append(currentMetadata)
defaults.setObject(allMetadata, forKey: "allMetadata")
func loadImageAtIndex(index: Int) -> UIImage {
let sketchPath: String = allMetadata[index].objectForKey("sketchpath") as String
let image = UIImage(contentsOfFile: sketchPath)
return image!
}
答案 0 :(得分:2)
您正在使用0 ... lengthOfSketchArray
的“封闭”范围,其中包括 零和lengthOfSketchArray
(即您将重复此lengthOfSketchArray + 1
次)。我认为您打算使用0 ..< lengthOfSketchArray
的“半开”范围,不包括lengthOfSketchArray
,即它将从零变为lengthOfSketchArray - 1
:
let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
for index in 0 ..< lengthOfSketchArray {
let path = documentsFolder.stringByAppendingPathComponent("Sketch\(index).png")
if let image = UIImage(contentsOfFile: path) {
slideSketchArray[index] = image
}
}
顺便说一下,我正在使用NSSearchPathForDirectoriesInDomains
来查找Documents文件夹。显然,在保存图像时你也会使用相同的技术。
此外,上面假设您已经声明并实例化了此数组。例如,如果它是一个Swift数组,例如
var slideSketchArray = [UIImage]()
答案 1 :(得分:0)
'...'表示您将lengthOfSketchArray作为迭代器的最后一个值。也许这就是为什么它在最后一个值崩溃导致它超出你的数组长度。你应该使用(lengthOfSteckArray-1)或..而不是......(我在Swift书中读过,但我不是100%)。无论如何,在包装它以获取值之前,您应该验证您的可选变量是否具有值。然后,使用NSSearchPathForDirectoriesInDomains检索Documents文件夹的路径
var documentDir: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
if lengthOfSketchArray > 0 {
for indexNumber in 0..lengthOfSketchArray {
let sketchPath: String = documentDir.stringByAppendingPathComponent("Sketch\(indexNumber).png")
let image = UIImage(contentsOfFile: sketchPath)
slideSketchArray[indexNumber] = image!
}
}