如何在Objective-C中将变量添加到类别?

需要创建一个带有新变量的类别(类型为NSArray).

OriginalClass Extension.h:

@interface OriginalClass (Extension) {
    NSArray *_array;
}

@property (nonatomic,retain) NSArray *array;

@end

但是我得到了错误:无法在@interface或@protocol中声明变量.

请帮忙解决问题.

解决方法

正如另一方所说,你不能.虽然有H2CO3指出,你可以使用 associative references.在 Apple Documents

Note that a category can’t declare additional instance variables for
the class; it includes only methods. However,all instance variables
within the scope of the class are also within the scope of the
category. That includes all instance variables declared by the class,
even ones declared @private.

如果你想去关联对象,你可以使用this答案.此外,您可以使用Ole Begemann的this帖子.

相关文章

首先GDB是类unix系统下一个优秀的调试工具, 当然作为debug代...
1. C语言定义1个数组的时候, 必须同时指定它的长度.例如:int...
C++的auto关键字在C+⬑新标准出来之前基本...
const关键字是用于定义一个不该被改变的对象,它的作用是告诉...
文章浏览阅读315次。之前用C语言编过链表,这几天突然想用C+...
文章浏览阅读219次。碰到问题就要记录下来,防止遗忘吧。文章...