Runtime

2020-08-08  本文已影响0人  KeepOnline

面试题

1.讲一下OC的消息机制

2.什么是Runtime?平时项目中有用过吗?

3.打印结果分别是什么?
    @interface KPLStudent : KPLPerson
    @end
    
    @implementation KPLStudent
    
    - (instancetype)init {
        if (self = [super init]) {
            NSLog(@"[self class] = %@", [self class]);
            NSLog(@"[super class] = %@", [super class]);
            NSLog(@"[self superclass] = %@", [self superclass]);
            NSLog(@"[super superclass] = %@", [super superclass]);
        }
        return self;
    }
    
    @end
    
    @interface KPLPerson : NSObject
    @end
    
    BOOL res1 = [[NSObject class] isKindOfClass:[NSObject class]];
    BOOL res2 = [[NSObject class] isMemberOfClass:[NSObject class]];
    BOOL res3 = [[KPLPerson class] isKindOfClass:[KPLPerson class]];
    BOOL res4 = [[KPLPerson class] isMemberOfClass:[KPLPerson class]]; 
    NSLog(@"%d %d %d %d", res1, res2, res3, res4);
4.以下代码能不能执行成功?如果可以,打印结果是什么?
    @interface KPLPerson : NSObject
    @propety (copy, nonatomic) NSString *name;
    @end
    @implementation
    - (void)print {
        NSLog(@"my name's %@", self.name);
    }
    @end
    
    @implementation
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        id cls = [KPLPerson class];
        void *obj = &cls;
        [(__bridge id)obj print];
    }
    
    @end

objc_msgSend执行流程01-消息发送

objc_msgSend执行流程02-动态方法解析

动态添加方法

    + (BOOL)resolveInstanceMethos:(SEL)sel {
        if (sel == @selector(test)) {
            Method method = class_getInstanceMethod(self, @selector(other));
            class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
            return YES;
        }
        return [super resolveInstanceMethod:sel];
    }
    
    void other(id self, SEL _cmd) {
        NSLog(@"%@-%s--%s", self, sel_getName(_cmd), __func__);
    }
    
    + (BOOL)resolveClassMethod:(SEL)sel {
        if (sel == @selector(test)) {
            class_addMethod(self, sel, (IMP)other, @"v@:");
            return YES;
        }
        return [super resolveClassMethod:sel];
    }
    // Method可以理解为等价于struct method_t *
    
    
    @interface KPLPersom : NSObject
    @property (assign, nonatomic) int age;
    @end
    @implementation KPLPerson
    @dynamic age;
    @end
    
    // @dynamic是告诉编译器不用自动生成getter和setter的实现,等到运行时再添加方法实现
    

objc_msgSend的执行流程03-消息转发

生成NSMethodSignature

    NSMethodSignature *signature = [NSMethodSignature signatureWithObjCType:"i@:i"];
    NSMethodSignature *signature = [[[KPLPerson alloc] init] methodSignatureForSelector:@selecote(test:)];

super的本质

    struct objc_super2 {
        id receiver;
        Class current_class;
    };
上一篇下一篇

猜你喜欢

热点阅读