向我的所有类添加自定义行为和状态

时间:2012-11-05 17:06:37

标签: iphone objective-c oop

我想在我的所有课程中添加功能和其他属性。


所以我写了一个类别:

@implementation NSObject (MyCategory)

我在其中声明了一个静态属性:

static MyObj myObj;

我创建了两个类方法来获取和设置它:

+ (MyObj) getMyObj {
    return myObj;
}

+ (void) setMyObj:(MyObj)obj {
    myObj = obj;
}

现在我在.pch文件中导入了NSObject + MyCategory.h,因此所有类都将受此影响。实际上,所有类都具有新的功能和状态:

#import "NSObject+MyCategory.h"

问题在于,当我设置myObj时,它会在所有类上更改myObj。所有班级共享1个myObj。

我希望每个班级都有自己的myObj ,使用该类别添加。我不想要一个myObj,而是我想要尽可能多的myObj作为类。每个类都应该有自己的myObj。

谢谢, 诺尔

2 个答案:

答案 0 :(得分:2)

您无法将属性实例变量添加到类别中的类中。子类NSObject或使用associated objects

答案 1 :(得分:0)

您的解决方案添加了单个静态变量(而不是“属性”,在Objective-C中意味着其他东西),没有办法使用类别为每个类添加静态变量。

但是你的想法接近于对你有用的东西;如果你只能有一个变量并且想要存储许多值你可以使用什么?字典。

static NSMutableDictionary *References;

+ (void) load
{
   // load is called exactly once when this category is first loaded,
   // setup the dictionary
   References = [NSMutableDictionary new];
}

+ (void) setMyObj:(MyObj)reference
{
   // NSMutableDictionary will take any object reference as a key,
   // for a class method self is a reference to the unique class object,
   // so use self as the key and store the reference
   [References setObject:reference forKey:self];
}

+ (MyObj) getMyObj
{
   // returns previously stored reference or nil if there isn't one for this class
   return [References objectForKey:self];
}

HTH