-1

I know in objective c you can not add instance variable in category of interface. that is ok but today i see something i can not figure it out ,(why is this behavior right?)

@interface XXXX:NSObject

@end

@interface XXXX(){

@private

    int x;
}

@end

why can i add add instance variable in empty () category , also why no one mention in in the internet.

Thanks All

pbx
  • 1,137
  • 7
  • 15
  • 2
    The empty category is a class extension. Have a look at http://stackoverflow.com/questions/7136124/class-extension-vs-class-category for more information. – mttrb Jun 14 '12 at 13:53

1 Answers1

3

You can add instance variables to anonymous categories/class extensions (Using just () for the category name), because they are essentially just a private extension of the main interface, and there can only be one.

However you cannot add new instance variables with named categories. You can make use of Associative References to work around this however.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • 1
    Actually, you can do this as of Apple's latest Objective-C language revisions. But you can't if you're still using the 32-bit Mac ABI, as it's not able to accommodate the new language features. – Jonathan Grynspan Jun 14 '12 at 14:05
  • Is that for all categories or just anonymous/class categories? – Mike Weller Jun 14 '12 at 14:08
  • this code complies with Xcode 4.1 for ios with not problems. i just want to know why is this allowed is there any resource i can find this info in. – Ali Alzyoud Jun 14 '12 at 14:08
  • I updated my answer. You can add instance variables to class categories. But not named ones. – Mike Weller Jun 14 '12 at 14:11
  • actually i found good info here: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html – Ali Alzyoud Jun 14 '12 at 14:14
  • 2
    It's not a category, it's an extension. Class extensions can do this; categories *cannot*. – Jonathan Grynspan Jun 14 '12 at 15:32
  • The syntactic difference is that an extension has no name, i.e. `()`, while a category has a name. (Apart from the value assigned to `__func__`, there's no practical difference between a method in a category and one in an extension.) – Jonathan Grynspan Jun 14 '12 at 15:35
  • Not true; there are a number of significant differences between a category and a class extension. Extensions can promote readonly->readwrite in properties, can add ivars, can add synthesize properties, and are true extensions of @interface. Categories are informal additions to a class, interface or interface+implementation, but cannot do the above. – bbum Jun 14 '12 at 17:08