一、class 结构(方法步骤)
struct objc_class {
//类本身
Class _Nonnull isa ;
//父类
Class _Nullable super_class
//类名
const char * _Nonnull name
long version
long info
//类大小
long instance_size
//类中的变量
struct objc_ivar_list * _Nullable ivars
//类中的变量
struct objc_method_list * _Nullable * _Nullable methodLists
//缓存,便于下次查找
struct objc_cache * _Nonnull cache
//类中的协议
struct objc_protocol_list * _Nullable protocols
} OBJC2_UNAVAILABLE;
- 1、[[NSObject alloc] init]初始化步骤
/*
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100
struct objc_class {
Class isa // 类本身 --> {isa; methodLists(alloc)(类方法)}
Class super_class ;
const char *name ;
long version ;
long info ;
long instance_size ;
struct objc_ivar_list *ivars ;
struct objc_method_list **methodLists // 实例方法 ;
struct objc_cache *cache ;
struct objc_protocol_list *protocols ;
}
最终指向自己,形成了一个闭环, NSObject的isa 不是指向一个nil
1 [EOCObject alloc] 先执行,因为EOCObject检测,没有alloc方法, 就去父类里面去查找。
2 检测父类是否响应 alloc, 如果有,那么执行, 开始分配内存空间大小(成员变量)。// 方法(类有关系)
3 init 方法,检测是否响应,如果没有去父类查找。
4 方法执行完,会存缓存(所以一般第二次操作,会更快)
*/
MyObject * objc = [[MyObject alloc] init];
30:18
二、方法 method(编码)
- 1、以object_开头里面参数修饰对象;以class_开头里面参数修饰类。
MyObject * objc = [[MyObject alloc] init];
//获取类中的isa指针
Class cls = object_getClass(objc);
Class cls2 = class_getSuperclass([objc class]);
- 2、元类:元类就是类对象所属的类
解释见链接:https://blog.csdn.net/beclosedtomyheart/article/details/50164353
Class metaIsa = objc_getMetaClass("MyObject");
NSLog(@"metaIsa = %@",metaIsa);
Class metaIsa2 = objc_getMetaClass("MyObjectInvalidate");
NSLog(@"MyObjectInvalidate = %@",metaIsa2);
运行结果:
metaIsa = MyObject
objc[1143]: class `MyObjectInvalidate' not linked into application
MyObjectInvalidate = (null)
- 3、object_getClass 与 class_getSuperclass 查看父类对象区别:object_getClass最终指向一个NSObject,class_getSuperclass最终指向一个nil
MyObject * objc = [[MyObject alloc] init];
Class objcClass = object_getClass(objc);
NSLog(@"%@--->%p",objcClass,objcClass);
//获取MyObject类中的isa指针的对象
//1
Class objcClassOneGrade = object_getClass(objcClass);
NSLog(@"%@--->%p",objcClassOneGrade,objcClassOneGrade);
//2
Class objcClassTwoGrade = object_getClass(objcClassOneGrade);
NSLog(@"%@--->%p",objcClassTwoGrade,objcClassTwoGrade);
//3
Class objcClassThreeGrade = object_getClass(objcClassTwoGrade);
NSLog(@"%@--->%p",objcClassThreeGrade,objcClassThreeGrade);
//4
Class objcClassFourGrade = object_getClass(objcClassThreeGrade);
NSLog(@"%@--->%p",objcClassFourGrade,objcClassFourGrade);
运行结果:
MyObject--->0x10e8a8ef0
MyObject--->0x10e8a8ec8
NSObject--->0x10f85ce58
NSObject--->0x10f85ce58
NSObject--->0x10f85ce58
Class objcSuperClass = class_getSuperclass([MyObject class]);
NSLog(@"%@--->%p",objcSuperClass,objcSuperClass);
Class objcSuperClassOneGrade = class_getSuperclass(objcSuperClass);
NSLog(@"%@--->%p",objcSuperClassOneGrade,objcSuperClassOneGrade);
Class objcSuperClassTwoGrade = class_getSuperclass(objcSuperClassOneGrade);
NSLog(@"%@--->%p",objcSuperClassTwoGrade,objcSuperClassTwoGrade);
Class objcSuperClassThreeGrade = class_getSuperclass(objcSuperClassTwoGrade);
NSLog(@"%@--->%p",objcSuperClassThreeGrade,objcSuperClassThreeGrade);
NSObject--->0x10c44aea8
(null)--->0x0
(null)--->0x0
(null)--->0x0
- 4、class_copyMethodList获取方法列表
@implementation MyObject
- (void)testMothod{
}
- (void)testMothod2:(NSString *)str{
}
- (void)testMothod3:(NSString *)str :(NSString *)str2{
}
@end
- (void)methodClass{
unsigned int cnt = 0;
Method * methods = class_copyMethodList([MyObject class], &cnt);
for (int i = 0; i < cnt; i ++) {
Method method = methods[i];
SEL sel = method_getName(method);
const char * agru = method_getTypeEncoding(method);
NSLog(@"%s----%s",sel_getName(sel),agru);
}
}
testMothod----v16@0:8
testMothod2:----v24@0:8@16
testMothod3::----v32@0:8@16@24
- 5、Method
Method结构
struct objc_method {
//方法名
SEL _Nonnull method_name
//参数
char * _Nullable method_types
//实现
IMP _Nonnull method_imp
}
- (void)viewDidLoad {
[super viewDidLoad];
[self excuteImp];
}
- (void)methodIMP{
NSLog(@"%s",__func__);
}
+ (void)methodClassImp{
NSLog(@"%s",__func__);
}
- (void)excuteImp{
//获取类方法
Method method = class_getClassMethod([self class], @selector(methodClassImp));
//获取实例方法
Method method2 = class_getInstanceMethod([self class], @selector(methodIMP));
IMP imp = method_getImplementation(method);
IMP imp2 = method_getImplementation(method2);
IMP imp3 = class_getMethodImplementation([self class], @selector(methodIMP));
imp();
imp2();
imp3();
}
打印结果:
+[ViewController methodClassImp]
-[ViewController methodIMP]
-[ViewController methodIMP]
- 6、Method参数编码规则:
V void
i int
@ oc对象
: 方法
# 类Class
B Bool
d double
f float
q NSInteger
数字:偏移量
- (void)viewDidLoad {
[super viewDidLoad];
[self excuteImp];
[self scanInvocation];
}
- (void)methodIMP:(NSString *)str andInt:(NSInteger)cnt{
}
- (void)scanInvocation{
NSMethodSignature * signature = [self methodSignatureForSelector:@selector(methodIMP:andInt:)];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:signature];
NSLog(@"signature = %@",signature);
NSLog(@"invocation = %@",invocation);
}
- (void)excuteImp{
//获取实例方法
Method method = class_getInstanceMethod([self class], @selector(methodIMP:andInt:));
const char * argu = method_getTypeEncoding(method);
NSLog(@"argu = %s",argu);
}
结果:
argu = v32@0:8@16q24
命令:po invocation
return value: {v} void
target: {@} 0x0
selector: {:} null
argument 2: {@} 0x0
argument 3: {q} 0
命令:po signature
number of arguments = 4
frame size = 224
is special struct return? NO
return value: -------- -------- -------- --------
type encoding (v) 'v'
flags {}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 0, size adjust = 0}
memory {offset = 0, size = 0}
argument 0: -------- -------- -------- --------
type encoding (@) '@'
flags {isObject}
modifiers {}
frame {offset = 0, offset adjust = 0, size = 8, size adjust = 0}
memory {offset = 0, size = 8}
argument 1: -------- -------- -------- --------
type encoding (:) ':'
flags {}
modifiers {}
frame {offset = 8, offset adjust = 0, size = 8, size adjust = 0}
memory {offset = 0, size = 8}
argument 2: -------- -------- -------- --------
type encoding (@) '@'
flags {isObject}
modifiers {}
frame {offset = 16, offset adjust = 0, size = 8, size adjust = 0}
memory {offset = 0, size = 8}
argument 3: -------- -------- -------- --------
type encoding (q) 'q'
flags {isSigned}
modifiers {}
frame {offset = 24, offset adjust = 0, size = 8, size adjust = 0}
memory {offset = 0, size = 8}
- 7、给对象添加方法
void testCMehtod(id self, SEL _cmd, NSString *argu){
//_cmd在Objective-C的方法中表示当前方法的selector
NSLog(@"%@--%s--%@", self,_cmd,argu);
}
- (void)addCMehod{
class_addMethod([self class], @selector(testCMehtod), (IMP)testCMehtod, "v@:@");//v: 返回空类型,@:自己 ::SEL @:参数对象
[self performSelector:@selector(testCMehtod) withObject:@"asd"];
}
8、获取对象变量
- (void)ivarList{
unsigned int outCount = 0;
Ivar *eocIvarList = class_copyIvarList([ViewController superclass], &outCount);
NSLog(@"%p", self);
for (int i = 0; i < outCount; i++) {
Ivar ivar = eocIvarList[i];
id testIvar = [self valueForKey:[NSString stringWithUTF8String:ivar_getName(ivar)]];
NSLog(@"%p===offset:%td====%s::%s", &testIvar, ivar_getOffset(ivar), ivar_getName(ivar), ivar_getTypeEncoding(ivar));
}
}
1:31
三、分类
- 在分类中重写方法,通过runtime查不到该方法。分类中的方法并没有对改方法进行覆盖。
@implementation MyObject
- (void)testMethod:(NSString *)test{
NSLog(@"%s",__func__);
}
@end
@implementation MyObject (Runtime)
- (void)testMethod:(NSString *)test{
NSLog(@"runtime %s",__func__);
}
- (void)methodClass{
unsigned int cnt = 0;
Method * methods = class_copyMethodList([MyObject class], &cnt);
for (int i = 0; i < cnt; i ++) {
Method method = methods[i];
SEL sel = method_getName(method);
const char * agru = method_getTypeEncoding(method);
NSLog(@"%s----%s",sel_getName(sel),agru);
}
}
运行结果:
testMethod:----v24@0:8@16
testMethod:----v24@0:8@16
4、类簇
-
setObject:forKey
与setValue:forKey:
的区别
前者的Object不可以为空,否者会产生崩溃;后者的Value可以为空,当为空是,会调用removeObjectForKey
方法。 - 利用runTime解决
setObject:forKey:
为空的情况
#import
@implementation NSMutableDictionary (Exception)
+ (void)load{
[self resolveNilExceptionMethod];
}
+ (void)resolveNilExceptionMethod{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
SEL originalSel = NSSelectorFromString(@"setObject:forKey:");
SEL exceSel = @selector(handleExcetion:forKey:);
NSLog(@"object_getClass(dict) = %@",object_getClass(dict));
NSLog(@"object_getClass(dict) = %@",[NSMutableDictionary class]);
Method method1 = class_getInstanceMethod(object_getClass(dict), originalSel);
Method method2 = class_getInstanceMethod(object_getClass(dict), exceSel);
method_exchangeImplementations(method1, method2);
}
- (void)handleExcetion:(id)anObject forKey:(id)aKey{
if (anObject == nil) {
NSLog(@"空对象");
anObject = @"";
}
[self handleExcetion:anObject forKey:aKey];
}
@end