如何在Objective-C中将变量添加到类别? [英] How to add a variable to category in Objective-C?

查看:166
本文介绍了如何在Objective-C中将变量添加到类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It's requied to create a category with a new variable (of type NSArray).

OriginalClass + Extension.h:

OriginalClass+Extension.h:

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

@property (nonatomic, retain) NSArray *array;

@end

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

But I got the error: Cannot declare variable inside @interface or @protocol.

请帮助解决问题。

推荐答案

正如另一方所述,你不能。虽然有H2CO3指出,你可以使用关联参考。在 Apple Documents

As the other stated, you can't. Although has H2CO3 pointed out, you can use associative references. On Apple Documents:


注意,类别不能为
类声明额外的实例变量;它只包括方法。但是,类范围内的所有实例变量
也在
类别的范围内。这包括类声明的所有实例变量,
甚至声明@private。

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.

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

If you want to go for associated object, you can use this answer. Moreover, you can use this post by Ole Begemann.

这篇关于如何在Objective-C中将变量添加到类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆