1

For Objective-C, in the following header file:

@interface Peg : NSObject {
    char color;
}

@property char color;

I wonder if the member variable is already said to be a char type, then why does the @property has to repeat it? (or else it won't compile). Couldn't the compiler tell that it is char? It couldn't be anything else, could it?

Nikita Pestrov
  • 5,876
  • 4
  • 31
  • 66
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

3 Answers3

7

That is because generaly properties don't have to be related to any declared instance variable of your class. You may have a property and not include a variable into your class header. That's why you have to declare it's type.

Using properties instead of variables makes your headers clean, hiding the implementation.

So, you can just declare a property and then @synthesize it

@interface Peg : NSObject

@property char color;


@implementation Peg

@synthesize color;

@end
Nikita Pestrov
  • 5,876
  • 4
  • 31
  • 66
  • does that mean in general it is more concise to leave out the instance variable? Leave out or not, there is still a `color` property to use? – nonopolarity Apr 14 '12 at 09:10
  • 1
    You can leave out the curly braces, too. `@interface Peg : NSObject @property char color;` and so on. – jscs Apr 14 '12 at 17:54
  • Here is a talk on proprties and variables,at the bottom http://stackoverflow.com/questions/155964/what-are-best-practices-that-you-use-when-writing-objective-c-and-cocoa – Nikita Pestrov Apr 14 '12 at 22:23
2

Actually, it's no longer needed, at least when compiling for x64 with clang. If you omit instance variable, @synthesize will create one for you.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
1

Just use The following

@interface Peg : NSObject {}

@property char color;
Abramodj
  • 5,709
  • 9
  • 49
  • 75