weak singleton
+ (id)shareInstance { static __weak ASingletonClass *instance; ASingletonClass *strongInstance = instance; @synchronized(self) { if (strongInstance == nil) { strongInstance = [[[self class] alloc] init]; instance = strongInstance; } } return strongInstance;}复制代码
weak associated object
- (void)setContext:(CDDContext *)object { id __weak weakObject = object; id (^block)() = ^{ return weakObject; }; objc_setAssociatedObject(self, @selector(context), block, OBJC_ASSOCIATION_COPY);}- (CDDContext *)context { id (^block)() = objc_getAssociatedObject(self, @selector(context)); id currentContext = (block ? block() : nil); return currentContext;}复制代码
KVO
Father
// .h#import@interface Father : NSObject- (void)methodToBeInherit;@end// .m#import "Father.h"@implementation Father- (void)methodToBeInherit { NSLog(@"Father Log");}@end复制代码
Son
// .h#import "Father.h"@interface Son : Father- (void)methodToBeInherit;@end// .m#import "Son.h"@implementation Son- (void)methodToBeInherit {// [super methodToBeInherit]; struct objc_super superInfo = { .receiver = self, .super_class = class_getSuperclass(object_getClass(self)) }; void (*objc_msgSendSuperMethod)(void *, SEL) = (void *)objc_msgSendSuper; objc_msgSendSuperMethod(&superInfo, _cmd); NSLog(@"Son Log");}@end复制代码
Son *son = [[Son alloc] init];[son methodToBeInherit];复制代码
结果如下:
假如现在我们想要实现上述结果,但是不是用son,而是Father呢?如何实现?
// .h#import@interface NSObject (Hook)- (void)isaSwizzingMethod;@end// .m#import "NSObject+Hook.h"#import "Son.h"#import @implementation NSObject (Hook)- (void)isaSwizzingMethod { Class newClass = [Son class]; object_setClass(self, newClass);}@end复制代码
Father *father = [[Father alloc] init];[father isaSwizzingMethod]; [father methodToBeInherit];复制代码
结果如下:
惊不惊喜,意不意外。
面向切面编程框架Aspects中有更多实现细节,感兴趣的可以去github下载demo一饱眼福。