美文网首页
Swift do catch捕获OC NSException异常

Swift do catch捕获OC NSException异常

作者: VervertomJC | 来源:发表于2024-07-24 10:43 被阅读0次

    参考:
    https://stackoverflow.com/questions/32758811/catching-nsexception-in-swift
    https://github.com/jonbrooks/ObjCTryCatch/blob/master/ObjCTryCatch/ObjCTryCatch.m

    
    #import <UIKit/UIKit.h>
    
    //! Project version number for ObjCTryCatch.
    FOUNDATION_EXPORT double ObjCTryCatchVersionNumber;
    
    //! Project version string for ObjCTryCatch.
    FOUNDATION_EXPORT const unsigned char ObjCTryCatchVersionString[];
    
    @interface ObjCTry <__covariant T>: NSObject
    
    /**
     * wraps `block` in an Objective C try block, catching any exceptions
     * and returning them in the user info of the returned error.  This will
     * import into swift as a throwing function that throws the error. 
     */
    + (BOOL)doTry:(void(^)())block error:(NSError **)err;
    
    /**
     * Same as above, but used for blocks that produce an Objective C object.
     */
    + (T)doTryObj:(T(^)())block error:(NSError **)err;
    
    @end
    
    #import <Foundation/Foundation.h>
    #import "ObjCTryCatch.h"
    
    @implementation ObjCTry
    
    + (BOOL)doTry:(void(^)())block error:(NSError **)err {
        @try {
            block();
            return YES;
        }
        @catch (NSException *exception) {
            *err = [NSError errorWithDomain:@"todo" code:1 userInfo:@{@"exception": exception}];
        }
        return NO;
    }
    
    + (id)doTryObj:(id(^)())block error:(NSError **)err {
        @try {
            return block();
        }
        @catch (NSException *exception) {
            *err = [NSError errorWithDomain:@"todo" code:1 userInfo:@{@"exception": exception}];
        }
        return nil;
    }
    @end
    
    

    相关文章

      网友评论

          本文标题:Swift do catch捕获OC NSException异常

          本文链接:https://www.haomeiwen.com/subject/mebuhjtx.html