質問

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

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.

"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

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 ?

役に立ちましたか?

解決

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).

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;
}

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top