1. List the classes in which methods need to be prefixed
+ (NSArray *)classesToSwizzle{ return @[ [NSManagedObject class], [NSManagedObjectContext class], [NSManagedObjectModel class], [NSPersistentStore class], [NSPersistentStoreCoordinator class] ]; }Copy the code
2, hook each class’s resolveClassMethod: and resolveInstanceMethod: methods
3, implement custom MR_resolveClassMethod: and MR_resolveInstanceMethod: methods, in the method for the call without prefix to add
static BOOL MRAddShorthandMethodForPrefixedInstanceMethod(Class objectClass, SEL originalSelector, NSString *prefix){ NSString *originalSelectorString = NSStringFromSelector(originalSelector); if ([originalSelectorString hasPrefix:prefix] == NO && ([originalSelectorString hasPrefix:@"_"] || [originalSelectorString hasPrefix:@"init"])) { NSString *prefixedSelector = [prefix stringByAppendingString:originalSelectorString]; Method existingMethod = class_getInstanceMethod(objectClass, NSSelectorFromString(prefixedSelector)); if (existingMethod) { BOOL methodWasAdded = class_addMethod(objectClass, originalSelector, method_getImplementation(existingMethod), method_getTypeEncoding(existingMethod)); return methodWasAdded; } } return NO; }Copy the code
Reference MagicalRecord (ShorthandMethods)