0x001 理解iOS的[self class] 和 [super class]
1、定义LGPerson
类
LGPerson.h
@interface LGPerson : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
GLPerson.m
@implementation LGPerson
@end
2、定义LGStudent
类,继承自LGPerson
LGStudent.h
@interface LGStudent : LGPerson
@end
LGStudent.m
#import <objc/message.h>
@implementation LGStudent
- (instancetype)init {
self = [super init];
if ( self ) {
// self class 方法 --- objc_msgSend
NSLog(@"[self class] == %@", NSStringFromClass([self class]));
// super class 方法 --- objc_msgSendSuper
NSLog(@"[super class] == %@", NSStringFromClass([super class]));
}
return self;
}
@end
3、输出结果为
2021-01-19 10:42:33.788113+0800 [self class] == LGStudent
2021-01-19 10:42:36.038494+0800 [super class] == LGStudent
4、分析
[self class]可以翻译为
objc_msgSend(self, @selector(class))
此时self为LGStudent的实例对象;
class实现如下:
- (Class)class {
// 返回类对象
return object_getClass(self);
}
[super class]可翻译为
objc_msgSendSuper(super, @selector(class))
这里super的结构体如下:
struct objc_super {
/// Specifies an instance of a class.
__unsafe_unretained _Nonnull id receiver;
/// Specifies the particular superclass of the instance to message.
__unsafe_unretained _Nonnull Class super_class;
/* super_class is the first class to search */
};
那么super可以定义为:
super = objc_super(
self,
class_getSuperclass([self class])
)
这里会去LGPerson
中查找方法的实现,但是receiver
消息接收者还是LGStudent
,所以输出结果如上了。
网友评论