我为 NSDictionary 定义了一个类别
NSDictionary+AddMyFunc.m
// Compiler error: expected identifier or '('
@implementation NSDictionary (AddMyFunc) {
NSInteger myNum;
}
- (void)myFunc {
//Compiler error: use of undeclared identifier 'myNum'
myNum = //some operation
}
@end
我想定义一个实例变量 myNum
,我按照上面的方式做了,但是我得到了上面显示的编译器错误。
为什么我会收到这些错误,如何消除它们?
最佳答案
您可以使用关联对象向类别添加属性
#import <objc/runtime.h>
static const void *ImageTagKey = &ImageTagKey;
@implementation UIImage (Tagged)
- (void)setTag:(NSSting *)tag
{
objc_setAssociatedObject(self, ImageTagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)tag
{
return objc_getAssociatedObject(self, ImageTagKey);
}
@end
关于ios - 在类别中声明实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121274/