OC调用私有方法

2019-10-08  本文已影响0人  huoshe2019

私有方法调用共有以下四种方式:
以Person类为例:

#import "Person.h"
@implementation Person
- (void)privateMethod
{
    NSLog(@"privateMethod");
}
@end

一、分类

#import "Person.h"
NS_ASSUME_NONNULL_BEGIN
@interface Person (Test)
//只有声明,没有实现
- (void)privateMethod;
@end
NS_ASSUME_NONNULL_END

调用方式如下:

Person *person = [[Person alloc] init];
[person privateMethod];

备注:

二、performSelector

调用方式如下:

Person *person = [[Person alloc] init];
[person performSelector:@selector(privateMethod) withObject:nil];

三、objc_msgSend

调用方式如下:

Person *person = [[Person alloc] init];
objc_msgSend(person,@selector(privateMethod));

四、IMP

调用方式如下:

Person *person = [[Person alloc] init];
IMP imp = [person methodForSelector:@selector(privateMethod)];
    void (* tempFunc)(id target, SEL) = (void *)imp;
    tempFunc(person, @selector(privateMethod));
上一篇 下一篇

猜你喜欢

热点阅读