How to properly handle NSFileHandle exceptions in Swift 2.0?

前端 未结 3 665
天涯浪人
天涯浪人 2020-12-29 06:02

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

3条回答
  •  离开以前
    2020-12-29 06:31

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

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

提交回复
热议问题