Visibility in Objective-C

For people whose computer background are from Java or C++, you would be amused by how Objective-C syntax doesn't seem to allow you to set the visibility of anything in your code. However, we have to look at this in a completely different view. Because Objective-C is a dynamic language by nature, some philosophies that do apply in Java and C++ do not apply to Objective-C. For instance, in Objective-C, there is no real protected/private methods. All methods are public. But don't panic yet, we have a workaround that will make an Objective-C methods looks like it's private.

Now let's look at Objective-C variables. Objective-C allows the same Java-like visibility modifier to instance variables. @private, for private variables (can be accessed only within the class). @protected for protected variables (can be accessed within the class and its subclasses), and @public, for public variables (can be accessed from any classes). Objective-C instance variables are protected by default.

Here's how you create a class with those protections:



To access protected/private instance variables from other classes, you will need to create an accessor/mutator or a property, but to access a public variable, you can access it like this:



Even though at compile time, those variables are protected from illegal access, however, since Objective-C is a dynamic language, you can use a setValue:forKeyPath: method on the object to set the value to an arbitrary variable, however, this practice is discouraged.

Method Visibility

As I mentioned earlier that all methods in Objective-C is public because it can be called (or to be technically correct, the message get sent to an object) even if we don't expose the method prototype in our header file. However, it is better to "hide" methods that we don't want to expose than not doing anything at all. The mechanism of hiding methods is to create an Objective-C category WITHIN the implementation file, thus we achieve the effect we want by hiding those methods but maintain how things should be in Objective-C. Here's the code snippet that shows you how to "hide" your methods.



Comments

Popular posts from this blog

Team work and Inner classes

The Interviews