runtime笔记一

时间:2021-07-24 05:47:49

一、iOS中_cmd

The _cmd variable is a hidden argument passed to every method that is the current selector

源码:

- (void)tryMessage
{
    SEL currentSel = _cmd;  // 通过_cmd关键字取到当前函数对应的SEL
    NSLog(@"currentSel is :%s",sel_getName(currentSel)); // C代码结果
    NSLog(@"currentSel is :%@",NSStringFromSelector(_cmd)); //O-C代码结果
}

得到结果:

-- :::] currentSel is :tryMessage
-- :::] currentSel is :tryMessage

二、Class 东东

第一遇到Class的时候,我记得是这里:

@interface NSObject <NSObject> {
    Class isa  OBJC_ISA_AVAILABILITY;
}
#if !OBJC_TYPES_DEFINED
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;

/// Represents an instance of a class.
struct objc_object {
    Class isa  OBJC_ISA_AVAILABILITY;
};

/// A pointer to an instance of a class.
typedef struct objc_object *id;
#endif
struct objc_class {
    Class isa  OBJC_ISA_AVAILABILITY;

#if !__OBJC2__
    Class super_class                                        OBJC2_UNAVAILABLE;
    const char *name                                         OBJC2_UNAVAILABLE;
    long version                                             OBJC2_UNAVAILABLE;
    long info                                                OBJC2_UNAVAILABLE;
    long instance_size                                       OBJC2_UNAVAILABLE;
    struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
    struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
    struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
    struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;

objc_class结构体

objc_class和objc_object分别是类结构体对象结构体,其中objc_object都有一个只想对象本身所属的类的isa指针,用她来处理很多事情。id代表ObjC对象,获取id对象的类;

三、IMP(Method Impletiontations)

/// A pointer to the function of a method implementation.
#if !OBJC_OLD_DISPATCH_PROTOTYPES
typedef void (*IMP)(void /* id, SEL, ... */ );
#else
typedef id (*IMP)(id, SEL, ...);
#endif

显而易见,IMP是一个函数指针,这是由编辑器生成的,当你发起一个ObjC消息之后,最终她会执行的那个代码,就是由这个函数指针指定的。