首先,我是 iOS 和 Swift 的新手,有 Android/Java 编程背景。所以对我来说,在尝试写入文件时捕获异常的想法是第二天性,以防空间不足、文件权限问题或文件可能发生的任何其他事情(根据我的经验,这已经发生了) .我也知道在 Swift 中,异常不同于 Android/Java 异常,所以这不是我在这里要问的。
我正在尝试使用 NSFileHandle 附加到文件,如下所示:
let fileHandle: NSFileHandle? = NSFileHandle(forUpdatingAtPath: filename)
if fileHandle == nil {
//print message showing failure
} else {
let fileString = "print me to file"
let data = fileString.dataUsingEncoding(NSUTF8StringEncoding)
fileHandle?.seekToEndOfFile()
fileHandle?.writeData(data!)
}
但是,seekToEndOfFile()
和 writeData()
函数都表明它们抛出了某种异常:
This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs. - Apple Documentation for
writeData()
那么在 Swift 2.0 中处理这个问题的正确方法是什么?我已经阅读了链接
Error-Handling in Swift-Language , try-catch exceptions in Swift , NSFileHandle writeData: exception handling , Swift 2.0 exception handling , 和 How to catch an exception in Swift ,但他们都没有直接回答我的问题。我确实读过一些关于在 Swift 代码中使用 objective-C 的内容,但由于我是 iOS 的新手,我不知道这个方法是什么,而且似乎无法在任何地方找到它。我还尝试了新的 Swift 2.0 do-catch
block ,但它们无法识别 NSFileHandle 方法会抛出任何类型的错误,这很可能是因为函数文档没有 throw 关键字。
我知道如果应用程序空间不足或其他原因,我可以让应用程序崩溃,但由于该应用程序稍后可能会发布到应用程序商店,我不希望这样。那么我该如何以 Swift 2.0 的方式做到这一点呢?
编辑:目前这是一个只有 Swift 代码的项目,所以尽管在 Objective-C 中似乎有办法做到这一点,但我不知道如何将两者结合起来。
最佳答案
第二个(可恢复的)解决方案是创建一个非常简单的 ObjectiveC++ 函数,它接受一个 block 并返回一个异常。
创建一个名为:ExceptionCatcher.h 的文件并将其添加到您的桥接 header 中(如果您还没有,Xcode 会提示为您创建一个)
//
// ExceptionCatcher.h
//
#import <Foundation/Foundation.h>
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
@try {
tryBlock();
}
@catch (NSException *exception) {
return exception;
}
return nil;
}
使用这个助手非常简单,我已经修改了上面的代码来使用它。
func appendString(string: String, filename: String) -> Bool {
guard let fileHandle = NSFileHandle(forUpdatingAtPath: filename) else { return false }
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else { return false }
// will cause seekToEndOfFile to throw an excpetion
fileHandle.closeFile()
let exception = tryBlock {
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
}
print("exception: \(exception)")
return exception == nil
}
关于ios - 如何正确处理 Swift 2.0 中的 NSFileHandle 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956002/