1. Define a box of ZBJPerson classes

@interface ZBJPerson : NSObject

@property (nonatomic, copy) NSString *name;

- (void)logName;
- (void)logSomething;

@end

#import "ZBJPerson.h"

@interface ZBJPerson()

@property(nonatomic, strong) NSNumber *weight;

@end

@implementation ZBJPerson

- (void)logName {
    NSLog(@"name:%@",_name);
}

- (void)logSomething {
    NSLog(@"something");
}

@end
Copy the code

2. Try interactive logName implementation in ZBJRuntimeExample.

#import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface ZBJRuntimeExample : NSObject - (void)exchangeImplementations; @end #import "ZBJRuntimeExample.h" #import <objc/runtime.h> #import "ZBJPerson.h" @interface ZBJRuntimeExample() @property(nonatomic, strong) ZBJPerson *person; @property (nonatomic, copy) NSString *name; @end @implementation ZBJRuntimeExample - (instancetype)init { self = [super init]; if (self) { _person = [ZBJPerson new]; } return self; } - (void)logName { // NSLog(@"my name is :%@", _person.name); // NSLog(@"my name is :%@", self.name); My name is: XXX NSLog(@"my name is :%@", [self valueForKey:@"_name"]); // [self logSomething]; [self performSelector:@selector(logSomething)]] } - (void)exchangeImplementations { _person.name = @"xxx"; self.name = @"123"; Method oriMethod = class_getInstanceMethod(_person.class, @selector(logName)); Method curMethod = class_getInstanceMethod(self.class, @selector(logName)); method_exchangeImplementations(oriMethod, curMethod); [_person logName]; } @endCopy the code

Note that ZBJRuntimeExample properties and methods cannot be used in the logName method of ZBJRuntimeExample. ZBJPerson attributes and methods should be used, in which case the logName self is ZBJPerson and not ZBJRuntimeExample. Properties can be KVC, methods can be performSelector.