时间:2010-07-23 18:23:52

标签: iphone nskeyedarchiver

5 个答案:

答案 0 :(得分:21)

答案 1 :(得分:5)

对于Swift 2.0:

func deleteFile(path: String) -> Bool{
    let exists = NSFileManager.defaultManager().fileExistsAtPath(path)
    if exists {
        do {
            try NSFileManager.defaultManager().removeItemAtPath(path)
        }catch let error as NSError {
            print("error: \(error.localizedDescription)")
            return false
        }
    }
    return exists
}

答案 2 :(得分:5)

Swift3示例:

do {
 try FileManager.default.removeItem(atPath: path)
} catch {
 // catch potential error
}

答案 3 :(得分:2)

对于Swift 2.0:

do {
  try NSFileManager.defaultManager().removeItemAtPath("Your_PATH")
} catch {

}

答案 4 :(得分:2)

对于Swift 3.0-> 4.1:

let fileManager = FileManager()
let fileName = "your_file_name"

//In Order to get your file path correctly
getFileURL(_ fileName: String) -> String? {
    let fileURL = fileManager.urls(for: fileManager.SearchPathDirectory.documentDirectory, in: fileManager.SearchPathDomainMask.userDomainMask).first
    return (fileURL?.appendingPathComponent(fileName).path)
}


//Persist Data
func persistData(_ data : Data) -> Bool{
     return NSKeyedArchiver.archiveRootObject(data, toFile: getFileURL(fileName)!)
}

//Get Persisted Data
func getArchivedData() -> Data?{
    return NSKeyedUnarchiver.unarchiveObject(withFile: getFileURL(fileName)!) as? Data
}

//Delete Persisted Data 
func deleteArchivedUser() -> Bool{
    do {
        try fileManager.removeItem(atPath: getFileURL(fileName)!)
        return true
    } catch _ {
        return false
    }
}