Skip to content

Properties and their instance variables

Nat! edited this page Mar 30, 2017 · 4 revisions

This is what happens, when you declare a @property in mulle-objc.

@property declaration in a class

  • all properties generate an instance variable of the same name, prepended with an underscore. This instance variable will not be visible in categories, due to compiler "issues"
  • all properties generate the accessors
  • if an instance variable of the same name has already been declared, it will be used
  • readonly properties also generate an instance variable

@property declaration in a protocol

  • When a class inherits a protocol containing a property, it does not automatically generate an instance variable for it. But it will generate accessors! The easist and most clear way is to respecify the property in the class again.

@property declaration in a category

  • No instance variable is created and no accessors are generated

Example

This will not work, as the instance variable is "hidden" to the category:

@interface Foo
@property( assign) int  x;
@end
@interface Foo(x)
- (void) printX
{
   printf( "%d\n", _x);
}
@end

It can be fixed thusly:

@interface Foo
{
    int   _x;
}
@property( assign) int  x;
@end