OGeek|极客世界-中国程序员成长平台

标题: ios - 在类别中声明实例变量 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 21:03
标题: ios - 在类别中声明实例变量

我为 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,我按照上面的方式做了,但是上面显示了编译器错误。 为什么会出现这些错误,如何消除它们?



Best Answer-推荐答案


您可以使用关联对象将属性添加到类别

#import <objc/runtime.h> 

static const void *ImageTagKey = &ImageTagKey;

@implementation UIImage (Tagged)

- (void)setTagNSSting *)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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4