1

In Objective-C, what is the actual difference between putting an instance variable in .h files vs. putting it in .m files? Is the end-result any different? What particular mechanism allows for this? How come this is possible in Objective-C and not in, say, C++?

If I adopt the style of putting instance variables in .m files, this is only suitable for private instance variables, right? I should always put my protected instance variables in .h files so they can be properly inherited by subclasses, right? Or is there a way to let protected ivars in .m files be inherited somehow?

1 Answer 1

2

Putting additional instance variables in class extensions was not possible prior to Clang/LLVM 2.0. Objective C compiler "assembles" the ivars of the class from the definitions in the header and in the class extension, arriving at the final layout.

Class extensions is a relatively new language feature of Objective-C, so its absence in other languages, such is C++, should come as no surprise. Yet other languages, such as C#, may implement a comparable feature with partial classes.

You are correct about the second part: only private instance variables and properties are suitable for use in class extensions; protected and of course public instance variables should be in the .h file.

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

Comments

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.