6

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.

aleroot
  • 71,077
  • 30
  • 176
  • 213
Dmitry
  • 14,306
  • 23
  • 105
  • 189

3 Answers3

4

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.

Community
  • 1
  • 1
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
3

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

Reference : here .

aleroot
  • 71,077
  • 30
  • 176
  • 213
2

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

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

  • 1
    @Altaveron perhaps associated objects can help you. (See my edited answer.) –  Oct 21 '12 at 18:17
  • 1
    A category allows you to add methods to an existing class. Period. See http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html – kamprath Oct 21 '12 at 18:17