美文网首页
OC调用私有方法

OC调用私有方法

作者: huoshe2019 | 来源:发表于2019-10-08 11:00 被阅读0次

    私有方法调用共有以下四种方式:
    以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));
    

    相关文章

      网友评论

          本文标题:OC调用私有方法

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