最近,我需要这样做(将状态添加到类别)。 @Dave DeLong对此有正确的看法。在研究最佳方法时,我发现Tom Harrington的一个很棒的blog post。我喜欢@ JeremyP关于在类别中使用@property声明的想法,但不是他的特定实现(不是全局单例的粉丝或持有全局引用)。联想参考是要走的路。
这是代码添加(看起来像)的ivars到您的类别。我详细地对此进行了博客here的博客。
在File.h,来电者只看到干净的,高层次的抽象:
@interface UIViewController (MyCategory)
@property (retain,nonatomic) NSUInteger someObject;
@end
在File.m,我们可以实现@property(注意:这些不能@ synthesize'd) :
@implementation UIViewController (MyCategory)
- (NSUInteger)someObject
{
return [MyCategoryIVars fetch:self].someObject;
}
- (void)setSomeObject:(NSUInteger)obj
{
[MyCategoryIVars fetch:self].someObject = obj;
}
我们还需要声明和定义类MyCategoryIVars。为了便于理解,我已经从正确的编译顺序中解释了这一点。 @接口需要放在Category @实现之前。
@interface MyCategoryIVars : NSObject
@property (retain,nonatomic) NSUInteger someObject;
+ (MyCategoryIVars*)fetch:(id)targetInstance;
@end
@implementation MyCategoryIVars
@synthesize someObject;
+ (MyCategoryIVars*)fetch:(id)targetInstance
{
static void *compactFetchIVarKey = &compactFetchIVarKey;
MyCategoryIVars *ivars = objc_getAssociatedObject(targetInstance, &compactFetchIVarKey);
if (ivars == nil) {
ivars = [[MyCategoryIVars alloc] init];
objc_setAssociatedObject(targetInstance, &compactFetchIVarKey, ivars, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[ivars release];
}
return ivars;
}
- (id)init
{
self = [super init];
return self;
}
- (void)dealloc
{
self.someObject = nil;
[super dealloc];
}
@end
上面的代码声明并实现了持有我们的ivars(someObject)的类。由于我们无法真正扩展UIViewController,这将不得不做。
你可以创建一个子类吗? – kennytm 2010-11-10 15:46:14