最近,我需要這樣做(將狀態添加到類別)。 @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