如何使用prepareForDeletion删除CoreData swift中的照片?

时间:2016-03-24 11:50:24

标签: ios swift core-data

我厌倦了解决这个问题但是当它删除它时删除其他照片路径,因为我使用.lastPathComponent enter image description here

   override func prepareForDeletion() {

    super.prepareForDeletion()
    if filePath != nil {

        let fileName = (filePath! as NSString).lastPathComponent

        let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true)[0]

        let pathArray = [dirPath, fileName]

        let fileURL = NSURL.fileURLWithPathComponents(pathArray)!

        do {
            try NSFileManager.defaultManager().removeItemAtURL(fileURL)
            try NSFileManager.defaultManager().removeItemAtPath(fileName)
        } catch let error as NSError {
            print("Error from prepareForDeletion - \(error)")
        }
    } else {
        print("filepath is empty")
    }
}

我明白了

检测到正确的filePath 这是正确的答案

 override func prepareForDeletion() {
   super.prepareForDeletion()

   if filePath != nil {

   if let imagePath = self.filePath {

     do {
         try NSFileManager.defaultManager().removeItemAtPath(imagePath)
     } catch let error as NSError {
         print("Error from prepareForDeletion - \(error)")
     }
   }
 } else {
print("filepath is empty")
    }
   }

2 个答案:

答案 0 :(得分:0)

为什么在“do”语句中有两个“remove”语句?请删除

try NSFileManager.defaultManager().removeItemAtPath(fileName

并检查错误是否仍然存在。

答案 1 :(得分:0)

不要将文件路径保存到数据库,只将文件名保存到数据库,然后在删除功能中创建路径。尝试这种方法。

{{1}}

}