3

I've seen a lot of codes that do this:

@interface Test0 : NSObject {
        @private int iVar;
}
@property (readwrite,assign) int iVar;
@end

and some other codes:

@interface Test0 : NSObject {
}
@property (readwrite,assign) int iVar;
@end

I know that you use the @synthesize iVar to tell the compiler to generate the getter and the setter methods for the property iVar.

My questions: do we need to declare the @private int iVar; instance variable? What the advantage of doing so? What is the best practice of declaring instance variables vs property? does the compiler link the instance variable with the property?

Thanks in advance.

1 Answer 1

5

Modern Objective-C runtimes and compilers that use non-fragile base classes (IIRC, the 64-bit runtime on OS X and the iOS 4.0 and higher runtimes) allow you to omit the instance variable. Your first example is required for older runtimes, the later is all that is required in modern runtimes.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your clarification, so for best practice and to be safe i should always use the first method?.
@Unis, if you are targeting modern runtime only, best practice would probably be to skip the instance variable; less code is better. If you need compatibility with older runtimes, you have no choice but to go with declaring the instance variable.
Skipping the ivar declaration could be better because it makes the header file look less cluttered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.