Instance variable declaration: best practices?

Discussion in 'iOS Programming' started by MacMan988, Jan 26, 2014.

  1. MacMan988 macrumors 6502a

    Jul 7, 2012
    Hi, I have seen instance variable being declared in various places such as in the header file, in the implementation file etc.




    What would be the best practice for declaring instance variables?
  2. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia
    It's a question of scope. iVars and properties declared in the header are visible to anybody that includes the header. iVars and properties declared in an "anonymous category" in the .m file are only visible in that file.

    Declaring things in the .m file is the rough equivalent to "private" scope in Java or C++. However, with introspection and KVC, nothing is truly private in Objective C.

    The problem with putting iVars in the .m file is that then they are not visible to subclasses of the class you re defining.

    What I do is to use iVars in the .h file for protected variable storage, and never access it from outside. I then use properties for publicly available storage.


Share This Page