NSObject+Extension.h
#import <Foundation/Foundation.h>
@interface NSObject (Extension)
- (id)performSelector:(SEL)selector withObjects:(NSArray *)objects;
@end
NSObject+Extension.m
#import "NSObject+Extension.h"
@implementation NSObject (Extension)
- (id)performSelector:(SEL)selector withObjects:(NSArray *)objects{
// 方法签名(方法的描述)
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
if (signature == nil) {
// @throw [NSException exceptionWithName:@"错误" reason:@"方法找不到" userInfo:nil];
[NSException raise:@"错误" format:@"%@方法找不到", NSStringFromSelector(selector)];
}
// NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值)
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = selector;
// 设置参数
NSInteger paramsCount = signature.numberOfArguments - 2; // 除self、_cmd以外的参数个数
paramsCount = MIN(paramsCount, objects.count);
for (NSInteger i = 0; i < paramsCount; i++) {
id object = objects[i];
if ([object isKindOfClass:[NSNull class]]) continue;
[invocation setArgument:&object atIndex:i + 2];
}
// 调用方法
[invocation invoke];
// 获取返回值
id returnValue = nil;
if (signature.methodReturnLength) { // 有返回值类型,才去获得返回值
[invocation getReturnValue:&returnValue];
}
return returnValue;
}
@end
在AppDelegate.m
中可以捕获异常
@implementation AppDelegate
/**
* 崩溃统计
* 1.友盟
* 2.Flurry
* 3.Crashlytics
*/
/**
* 拦截异常
*/
void handleException(NSException *exception){
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[@"callStack"] = [exception callStackSymbols]; // 调用栈信息(错误来源于哪个方法)
info[@"name"] = [exception name]; // 异常名字
info[@"reason"] = [exception reason]; // 异常描述(报错理由)
// [info writeToFile:<#(NSString *)#> atomically:<#(BOOL)#>];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 将沙盒中的错误信息传递给服务器
// 设置捕捉异常的回调
NSSetUncaughtExceptionHandler(handleException);
return YES;
}
@end