Pergunta

code1

@interface Rectangle : NSObject   
{
    int width,height;
}
@property int width,height;

code2

@interface Rectangle : NSObject
@property int width,height;
{
    int width,height;
}

Can anyone tell me, what is different between them? And in @property I already put int for width and height. Why do we need to declare it again in curly brackets?

Update: I am using osx 10.8 64bit.

Foi útil?

Solução

In your example "code1" is correct but possibly unneeded, while "code2" is incorrect and won't compile. Any instance variables need to be declared in curly brackets directly after the @interface line which is why the second example is wrong.

As some others has mentioned you may not need to declare width and height at all. If you are using the modern runtime the compiler can tell from the @property statement that you meant to have an underlying instance variable for the property and will create these for you. On the other hand with the older legacy runtime the instance variables like width and height must be explicitly declared. You didn't specify your platform so it is no clear if it is needed in your case.

The modern runtime is always used on iOS, which is why many people here will tell you incorrectly that the instance variables do not need to be declared in any case. On Mac OS X the modern runtime is used with 64-bit code in 10.5 or newer. If you are using 32-bit code or an older version you need to explicitly declare your instance variables.

Outras dicas

You don't have to redeclare, just use:

@interface Rectangle : NSObject
@property int width,height;
@end

The names inside the braces are instance variables which may or may not be used as backing storage for the matching properties. It depends on how you write your @synthesize statements.

I would prefer to not have explicit instance variables at all. The only reason I have used them in this kind of situation is to make debugging easier.

The difference between them is that the first one is right and the second one is wrong. Even if the second code compiles, that is not how you should write your code. Always put all property declarations after the ivars (the things in the curly brackets. And the @property doesn't declare the variables (that's done in the curly brackets). The @property directive gives instructions to the compiler on how to generate the getter and setter methods when you use the @synthesize directive, which you should do in your implementation file.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top