如果使用 static,子类方法与父类方法使用的会是同一个 static 变量。如果想要子类结果区分于父类,子类还需重新实现。
而使用 runtime,子类不需要写额外逻辑,就能够声明出绑定于 Class 的类变量。
这份微妙的差异请细细体会。
@interface BaseObject : NSObject
@property (nonatomic, class, strong) NSString *ClassName;
@end
@interface MyObject : BaseObject
@end
#import "BaseObject.h"
#import <objc/runtime.h>
static NSString * const kClassPropertiesKey = @"kClassPropertiesKey";
@implementation BaseObject
+ (void)setClassName:(NSString *)ClassName
{
objc_setAssociatedObject(self.class, &kClassPropertiesKey, ClassName, OBJC_ASSOCIATION_RETAIN);
}
+ (NSString *)ClassName
{
NSString *className = objc_getAssociatedObject(self.class, &kClassPropertiesKey);
if (!className)
{
objc_setAssociatedObject(self.class, &kClassPropertiesKey, NSStringFromClass(self.class), OBJC_ASSOCIATION_RETAIN);
className = objc_getAssociatedObject(self.class, &kClassPropertiesKey);
}
return className;
}
@end
@implementation MyObject
@end
NSLog(@"%@ %@", [BaseObject ClassName], [MyObject ClassName]); // BaseObject MyObject
网友评论