想法很好, 可总不能每个类里都加一个临时对象的属性吧. 那如何在不改变原有类的情况下, 为其关联一个临时对象呢?
关联属性
不改变原有类, 这时候肯定是要用Category了, 系统框架里面有很多的分类, 并且有很多的关联属性, 如下图 UIView 头文件第180行:

依照上图, 我们先看一个示例, 为NSObject的添加一个Category, 并添加了一个property, 在.m中实现了它的setter和getter方法.
#import <objc/message.h>
@interface NSObject (Associate)
@property (nonatomic, strong) id tmpObj;
@end
@implementation NSObject (Associate)
static const char *testKey = "TestKey";
- (void)setTmpObj:(id)tmpObj {
// objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
objc_setAssociatedObject(self, testKey, tmpObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)tmpObj {
// objc_getAssociatedObject(id object, const void *key)
return objc_getAssociatedObject(self, testKey);
}
@end
很明确, objc_setAssociatedObject 便是关联属性的setter方法, 而objc_getAssociatedObject便是关联属性的getter方法. 最需要关注的就是setter方法, 因为我们要用来添加关联属性对象.
初步思路探索
初步尝试:
既然属性可以随时使用objc_setAssociatedObject关联了, 那我就尝试先为self关联一个临时对象, 在其dealloc中, 将Observer移除.
@interface SJObserverHelper : NSObject
@property (nonatomic, weak) id target;
@property (nonatomic, weak) id observer;
@property (nonatomic, strong) NSString *keyPath;
@end
@implementation SJObserverHelper
- (void)dealloc {
[_target removeObserver:_observer forKeyPath:_keyPath];
}
@end
- (void)addObserver {
NSString *keyPath = @"name";
[_xiaoM addObserver:_observer forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:nil];
SJObserverHelper *helper_obj = [SJObserverHelper new];
helper_obj.target = _xiaoM;
helper_obj.observer = _observer;
helper_obj.keyPath = keyPath;
const char *helpeKey = [NSString stringWithFormat:@"%zd", [_observer hash]].UTF8String;
// 关联
objc_setAssociatedObject(_xiaoM, helpeKey, helper_obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
于是, 美滋滋的运行了一下程序, 当将_xiaoM 置为 nil 时, 砰 App Crash......
reason: 'An instance 0x12cd1c370 of class Person was deallocated while key value observers were still registered with it.
分析: 临时对象的dealloc, 确确实实的跑了. 为什么会还有registered? 于是我尝试在临时对象的dealloc中, 打印实例变量target, 发现其为nil. 好吧, 这就是Crash问题原因!










