向我的所有类添加自定义行为和状态 [英] Adding custom behavior and state to all my classes
问题描述
我想为我的所有类添加功能和另一个属性.
I want to add functionality and another property to ALL of my classes.
所以我写了一个类别:
@implementation NSObject (MyCategory)
我在其中声明了一个静态属性:
And I declared a static property in it:
static MyObj myObj;
我创建了 2 个类方法来获取和设置它:
And I created 2 class methods to get and set it:
+ (MyObj) getMyObj {
return myObj;
}
+ (void) setMyObj:(MyObj)obj {
myObj = obj;
}
现在我在我的 .pch 文件中导入了 NSObject+MyCategory.h,所以所有的类都会受到这个影响.事实上,所有的类现在都有新的功能和状态:
Now I imported NSObject+MyCategory.h in my .pch file, so all classes will be effected by this. Indeed all classes now have the new functionality and state:
#import "NSObject+MyCategory.h"
<小时>
问题是,当我设置 myObj 时,它会更改所有类的 myObj.所有类共享 1 个 myObj.
The problem is that when I set myObj, it changes myObj on all classes. All classes share 1 myObj.
我希望每个类都有自己的 myObj,它是使用类别添加的.我不想要一个 myObj,而是想要和类一样多的 myObj.每个类都应该有自己的 myObj.
I want each class to have its own myObj that is added using the category. I don't want one myObj, rather I want as many myObj's as classes. Each class should have its own myObj.
谢谢,努尔
推荐答案
您不能将 properties 实例变量添加到类别中的类.子类 NSObject 或使用 关联对象.
You can not add properties instance variables to a class in categories. Either subclass NSObject or use associated objects.
这篇关于向我的所有类添加自定义行为和状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!