1

I've noticed that I'm able to declare instance variables in the implementation file of an Objective-C class. I understand there's a reason why I've been taught not to do this. Explained here. But it's so much nicer to not put them in the header, and my code seems to be running fine. How is this going to bite me in the butt down the road?

1 Answer 1

4

There are two ways of declaring them in the implementation file.

Through a class continuation, which means placing another @interface block at the top of the file with an empty category name (they only JUST added the ability to add ivars here)

Or placing them just at the top of the file. When doing it like this, you are NOT adding ivars. This is the same as adding a variable to the top of a C file. They are in scope of the entire file, and every instance of the class that is in that file. These are global.

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

7 Comments

You can also declare @propertys in the class continuation, which will add an implicit instance variable.
Ah, ok, so when I've been just adding them at the top of the file I've been creating class-level variables. Very good to know. Thanks!
not really class level variables either. You were creating 'file scope' variables
This is a minor point, but variable declared at the top of a file have global scope, not file scope. The compiler will export the symbols from the object file, and any code compiled in the project can access those globals. If you declare global variables with the same names in two different files you'll get duplicate symbol link errors. If you declare these variables as static then they have translation unit scope, which is basically file scope (unless you're doing this in a header file, in which case you may be digging your own grave).
File scope vs. global scope seems like a pretty major point to me! Thanks.
|

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.