當不涉及到用戶隱私的時候历极,我們調用私有方法一般都沒有什么問題窄瘟。
在我們調用私有方法之前,我們必須要先知道你想調用的對象有哪些私有方法趟卸,和需要參數(shù)的那些方法的參數(shù)類型蹄葱,和返回值的類型是多少氏义。
查看私有方法名,參數(shù)類型和返回值類型
- (void)scanMethodsTwo:(Class)class {
unsigned int outCount = 0; // unsigned int :是無符號基本整型图云,沒有負數(shù)
Method *methods = class_copyMethodList(class, &outCount); // 獲取類的方法列表
for (int i = 0; i < outCount; i++) {
Method method = methods[i];
// 獲取方法名
SEL sel = method_getName(methods[i]);
NSLog(@"方法名==== %@", NSStringFromSelector(sel));
// 獲取參數(shù)
char argInfo[512] = {};
unsigned int argCount = method_getNumberOfArguments(method);
for (int j = 0; j < argCount; j++) {
// 參數(shù)類型
method_getArgumentType(method, j, argInfo, 512);
NSLog(@"參數(shù)類型=== %s", argInfo);
memset(argInfo, '\0', strlen(argInfo));
}
// 獲取方法返回值類型
char retType[512] = {};
method_getReturnType(method, retType, 512);
NSLog(@"返回值類型=== %s", retType);
}
free(methods);
}
調用無參數(shù)方法
當知道方法名過后惯悠,我們調用沒有參數(shù)的私有方法,有兩種:
方法一:使用performSelector來調用
[button performSelector:@selector(updateConstraints)];
方法二:也可以使用objc_msgSend來調用竣况,但是是有這個必須要導入#import <objc/runtime.h>克婶,#import <objc/message.h>這兩個頭文件。
((void(*)(id,SEL))objc_msgSend)(button, @selector(updateConstraints));
如果要使用下面這種寫法丹泉,必須要在項目配置文件 -> Build Settings -> Enable Strict Checking of objc_msgSend Calls 這個字段設置為 NO, 默認為YES.
objc_msgSend(button, @selector(updateConstraints));
調用有參數(shù)方法
要使用objc_msgSend來調用情萤,并傳遞參數(shù)
((void(*)(id,SEL, CGRect))objc_msgSend)(button, @selector(setFrame:), CGRectMake(200, 100, 50, 50));
objc_msgSend(button, @selector(setFrame:), CGRectMake(200, 100, 50, 50));