有关类别属性问题的问题很多.我知道解决这个问题的一些可能性:
从我的角度来看,两者都不干净,因为在创建此类属性的对象被释放时,永远不会清除分配的内存.
类别是保持代码清洁并向现有类动态添加功能的好方法.它们有助于将功能和分布式实现工作分组到更多开发人员中.
类别的坏处是缺少存储.
我现在多次遇到这个问题而且我想知道以下是否会以一种干净的方式解决这个问题,这也会照顾内存,如果有任何我现在看不到的问题.
有一个限制,我可以忽略,因为我是一个框架开发人员:我能够创建我自己的所有其他类可以继承的根类.
首先声明新的根对象:
@interface RootObject : NSObject
- (void)setRuntimeProperty:(id)runtimeProperty forKey:(id<NSCopying>)key;
- (id)runtimePropertyForKey:(id)key;
@end
Run Code Online (Sandbox Code Playgroud)
与相应的实现:
#import "RootObject.h"
@interface RootObject ()
@property (readwrite) NSMutableDictionary *runtimeProperties;
@end
@implementation RootObject
@synthesize runtimeProperties = _runtimeProperties;
- (id)init {
self = [super init];
if (self)
{
_runtimeProperties = [[NSMutableDictionary alloc] initWithCapacity:1];
}
return self;
}
- (void)dealloc {
[_runtimeProperties release];
_runtimeProperties = nil;
[super dealloc];
}
- (id)runtimePropertyForKey:(id)key {
return [self.runtimeProperties objectForKey:key];
} …Run Code Online (Sandbox Code Playgroud)