如何在Swift 2.0中正确处理NSFileHandle异常? [英] How to properly handle NSFileHandle exceptions in Swift 2.0?

查看:223
本文介绍了如何在Swift 2.0中正确处理NSFileHandle异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是iOS和Swift的新手,来自Android / Java编程背景。因此,对于我来说,尝试写入文件时捕获异常的想法是第二天性,如果缺少空间,文件权限问题或文件中可能发生的任何其他事情(根据我的经验,已发生) 。我也明白,在Swift中,异常与Android / Java不同,所以这不是我在这里要求的。

First of all, I am new to iOS and Swift and come from a background of Android/Java programming. So to me the idea of catching an exception from an attempt to write to a file is second nature, in case of lack of space, file permissions problems, or whatever else can possibly happen to a file (and has happened, in my experience). I also understand that in Swift, exceptions are different from Android/Java ones, so that's not what I'm asking about here.

我试图追加到文件使用NSFileHandle,如下所示:

I am attempting to append to a file using NSFileHandle, like so:

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()函数表示它们抛出某种异常:

However, both the seekToEndOfFile(), and writeData() functions indicate that they throw some kind of exception:


如果文件描述符已关闭或不是,则此方法引发异常如果接收器表示未连接的管道或套接字端点,如果文件系统上没有剩余空闲空间,或者发生任何其他写入错误,则有效。 - 的Apple文档writeData()

那么正确的方法是什么在Swift 2.0中处理这个问题?我已经阅读了链接
Swift-Language中的错误处理在Swift中尝试捕获异常 NSFileHandle writeData:异常处理 Swift 2.0异常处理,并如何捕获异常在斯威夫特,但他们都没有直接回答我的问题。我确实读过一些关于在Swift代码中使用objective-C的东西,但由于我是iOS新手,我不知道这个方法是什么,似乎无法在任何地方找到它。我还尝试了新的Swift 2.0 do-catch 块,但是他们没有意识到NSFileHandle方法会抛出任何类型的错误,很可能是因为函数文档有没有throw关键字。

So what is the proper way to handle this in Swift 2.0? I've read the links Error-Handling in Swift-Language, try-catch exceptions in Swift, NSFileHandle writeData: exception handling, Swift 2.0 exception handling, and How to catch an exception in Swift, but none of them have a direct answer to my question. I did read something about using objective-C in Swift code, but since I am new to iOS, I don't know what this method is and can't seem to find it anywhere. I also tried the new Swift 2.0 do-catch blocks, but they don't recognize that any type of error is being thrown for NSFileHandle methods, most likely since the function documentation has no throw keyword.

我知道我可以让应用程序崩溃,如果它用完了空间或其他什么,但因为应用程序可能会发布到应用程序商店以后,我不希望这样。那么我如何以Swift 2.0的方式做到这一点?

I am aware that I could just let the app crash if it runs out of space or whatever, but since the app will possibly be released to the app store later, I don't want that. So how do I do this the Swift 2.0 way?

编辑:这是一个只有Swift代码的项目,所以尽管看起来似乎在Objective-C中有一种方法可以做到这一点,我不知道如何将两者混合。

This currently is a project with only Swift code, so even though it seems there is a way to do this in Objective-C, I have no idea how to blend the two.

推荐答案

一秒钟(可恢复的解决方案是创建一个非常简单的ObjectiveC ++函数,它接受一个块并返回一个异常。

a second (recoverable) solution would be to create a very simple ObjectiveC++ function that takes a block and returns an exception.

创建一个名为ExceptionCatcher.h的文件并在你的文件中添加import桥接标题(如果您还没有标题,Xcode将提示为您创建一个)

create a file entitled: ExceptionCatcher.h and add import it in your bridging header (Xcode will prompt to create one for you if you don't have one already)

//
//  ExceptionCatcher.h
//

#import <Foundation/Foundation.h>

NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
    @try {
        tryBlock();
    }
    @catch (NSException *exception) {
        return exception;
    }
    return nil;
}

使用这个助手非常简单,我已经调整了上面的代码来使用它。

Using this helper is quite simple, I have adapted my code from above to use it.

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
}

这篇关于如何在Swift 2.0中正确处理NSFileHandle异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆