NSFileHandle writeData:异常处理 [英] NSFileHandle writeData: exception handling

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

问题描述

这可能是一个相当广泛的问题,但我找不到任何在线资源解决或解释此事。

This could be rather broad problem but I could not find any online resource addressing or explaining this matter.

问题是在创建 NSFileHandle之后* writer = [NSFileHandle fileHandleForWritingAtPath:path] 当你使用 [writer writedata:NSData] 时,有可能的正常异常可能根据苹果医生说火。

The question is after creating NSFileHandle *writer = [NSFileHandle fileHandleForWritingAtPath:"path"] and when you use [writer writedata:"NSData"] there are sine possible exception that could fire according to the apple doc.


如果文件描述符关闭或
无效,如果接收者代表未连接的管道,则此方法引发异常或者套接字
端点,如果文件系统上没有剩余空间,或者发生任何其他
写入错误。 - APPLE DOC

"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 DOC

我想知道的是,我们有什么方法可以处理或验证这些问题,而无需使用任何try catch或check对于写入前的条件检查中的每个错误。我们可以使用 NSError 来处理这个问题吗?

All I want to know is is there any way we can handle or validate these issues without using any try catch or checking for each error in a condition check before write. Any possible way we can use NSError to handle this ?

推荐答案

我会说不。如果你确实设法在写入之前找到涵盖所有可能的失败的测试,那么在初始测试之后没有什么可说的写操作可能会失败(考虑写入一个免费1KB的文件系统,你想写4KB)。

I would say "No". If you did manage to find a test that covered all possible failures before writing, then there is nothing to say that the write operation might fail after this initial test (think about writing to a filesystem with 1KB free and you want to write 4KB).

因此,在 @ try / @ catch 块中包含对这些方法的调用似乎是最好的方法。如果你想要失败的详细信息(你当然应该想要的话),这些包装器可以返回 NSError **

Therefore wrapping your calls to these methods inside a @try/@catch block would seem to me to be the best approach. These wrappers could then return an NSError ** if you want details of the failure (which you most certainly should want).

- (BOOL)writeData:(NSData *)data
     toFileHandle:(NSFileHandle *)fileHandler
            error:(NSError **)error
{
    @try
    {
        [fileHandler writeData:data];
    }
    @catch (NSException *e)
    {
        if (error != NULL)
        {
            NSDictionary *userInfo = @{ 
                NSLocalizedDescriptionKey : @"Failed to write data",
                // Other stuff?
            };
            *error = [NSError errorWithDomain:@"MyStuff" code:123 userInfo:userInfo];
        }
        return NO;
    }
    return YES;
}

你肯定想把失败的原因搞到 NSError ,但这对我来说并不是很明显如何去做。

You will certainly want to get the reason for the failure into the NSError, but it's not immediately obvious to me how to go about doing this.

这篇关于NSFileHandle writeData:异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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