Ok, so I was reading some articles regarding Good Programming Practices and I came across a statement which said that making all your Elements public for your classes isn’t a good idea.. aka The concept of Encapsulation.
Now in Objective C, When I create a element for my class, I do the following, consider an NSMutableArray
@property (nonatomic, retain) NSMutableArray* myArray;
WHY I DO THIS?
So as to give the Retain property to myArray and therefore, giving it a simpler Memory Management cycle. Later on, I initialize the myArray in viewDidLoad as
self.myArray = [NSMutableArray arrayWithCapacity:0];
Later in Dealloc…
self.myArray = nil;
WHAT ELSE HAPPENS
By giving this property and synthesizing myArray in .m file, what I am unknowingly doing is making Public Getters and Setters for all the elements of my class.
Also, the auto-generated UI Elements from Xib files, do have the same declarations applied.
That isn’t a nice idea to keep creating public Getters and setters for each and every element of your class, right?
So, there’s absolutely no kind of encapsulation applied! Please correct me if I am wrong here and help me with any solutions!
Thanks!
Simply use the principle of Class Extensions that allows you to put part of your declarations in your
.mfile, thus making it invisible in your header and invisible from other classes.(This is Apple’s recommended way to declare private methods and properties, by the way)
YourClass.hYourClass.mYou can even declare a property as readonly in your public interface (in the header file) and redeclare it as readwrite in your private interface (in the class extension in the
.mfile) for example.See the Apple documentation for more details.
Note that:
.h. In the latest version of the compiler (Modern Objective-C) there is even no need for the@synthesizedirective as it now generate it automatically if not present (see doc).mthe same way you would do in your.h. That’s a way to hide instance variables from the public header too. In general I really rarely use instance variables (as declaring only the properties is sufficient) and if I really need an ivar I declare it in the class extension to make it not visibile in the public header.