How to add a variable to category in Objective-C? [closed]

青春壹個敷衍的年華 提交于 2019-12-19 06:46:42

问题


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

OriginalClass+Extension.h:

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

@property (nonatomic, retain) NSArray *array;

@end

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

Please help to solve the problem.


回答1:


As the other stated, you can't. Although has H2CO3 pointed out, you can use associative references. On 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.

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




回答2:


You can't, a category can't declare additional instance variables ...

Reference : here .




回答3:


Simple: you can't add instance variables to a class using a category.

If you need to store additional data: use associated objects.



来源:https://stackoverflow.com/questions/13000693/how-to-add-a-variable-to-category-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!