Objective-C: do you use #private visibility/access modifier in your code? - iphone

There are 3 modifiers: #private, #protected (default) and #public. Being accustomed to do so in C++ and other more sane languages, I always use #private for my fields. I barely (if ever)see that in SDK examples from Apple - they just rely on the default one.
One day I realized that Objective-C inheritance is rather fake feature: deriving an interface from another one doesn't mean all private fields are now available for redefinition. The compiler still sees them and disallows defining a new private field with the the same name, which goes orthogonal with classic encapsulation paradigm in OOD.
So I am a bit frustrated. Maybe I am expecting too much from the language because it's nothing more than a build up over standard C.
So do you use #private in your code? Why?

I guess it's a good idea to always use #private, but I've never bothered in the past because I generally use property accessors for almost all ivar access except in init and dealloc methods. So in practice, I rarely have a problem of accessing ivars by mistake.
Also, if you're targeting iOS 4+, you don't need to declare ivars for properties if you use #synthesize.
I should note that if you're writing library code that is meant to be subclassed by other developers, the use of #private would be more important.

I do out of habit, but it really doesn't matter unless you're shipping a binary framework others will link agianst, which I'm pretty sure you're not doing.
All #private does is restrict the visibility of the members of the object struct (accessed like obj->_ivar, rather than [obj getter] or obj.getter). It's a nice sanity check since it will error if you try to do it outside the class -- pretty much the only place to use direct structure access is when implementing NSCoding or NSCopying and those will still work -- but it doesn't really buy you much.

It's only really useful for Apple or folks who are shipping libraries that want to expose certain fields only to themselves in header files. We never use it because the accessor model lets you expose (or not) what you want. Since I have both header and source files what good is private really? Objective-C isn't C++ so #private has a different purpose.

In all the code I've written in Objective-C since 1989, I've never bothered to use #public, #protected, or #private.

Related

If I am not overriding accessor methods in sub class in Objective C, is it safe to use

An old post explains pretty well: Why shoudn't I use accessor methods in init methods
But my question is:
Q. If I am not overriding accessor methods in sub class in Objective C, is it safe to use in init?
It is usually avoided to prevent KVO mechanisms from accessing a partially initialised or partially deallocated object. This is particularly true for Mac OS X development where bindings and KVO play a large part especially in an application's user interface. I'm not an iPhone developer but if KVO is used on the iPhone platform as well, then it may be reason enough to avoid using accessor methods in your init and dealloc methods.
KVO makes a dynamic subclass of your class so that it can easily monitor changes to properties.
It's easy enough to avoid them in init and dealloc. Some argue that it's easier to use the accessor methods everywhere regardless of Apple's recommendations, but the convention is to avoid using them for init and dealloc and following the convention usually means less hurt later even if you don't anticipate any problems now.
Best practices from Apple say don't use self. accessors when in init or dealloc methods. It'll probably be fine, but basically Apple can't guarantee it.
If I am not overriding accessor methods in sub class in Objective C, is it safe to use?
Answer: Never user self.accessor.
From my 2+ years working experience under 20+ years apple developers(cocoa,obj-c), what I learnt is same.
Many a times our team has been asked to remove all those and and guided to use some other design pattern or way, even though it was required.
This may put you under problem if the object was created as nonatomic, and many threads working on same property/object. self. makes your class/object bind-ed. As you have tagged ios, for previous versions of ios this could have been done, but now ios are supporing kvo, so you should not follow this way.

How to avoid accidental overriding method or property in Objective-C

For instance, I subclassed UILabel and added a method or property called -verticalTextAlignment to align text vertically.
And in the future, if next version of SDK or iOS added a method or property which has the same name, then it is possible my app crashs or behaves unexpectedly.
*This problem happens even if you use category instead of subclassing.
Question1
How to avoid this kind of accidental overriding in Objective-C?
I think you can avoid this by prefixing all of your methods and properties like -XXX_verticalTextAlignment. But it is not realistic, is it?
Question2
I know that this kind of accidental overriding happens at compiling time or when you update your iOS SDK, OSX SDK, or XCode.
But is it possible to happen also when updating your iPhone's iOS version?
For example, is it possible that your app runs well on iOS5 but doesn't run on iOS6 due to accidental overriding in iOS6.(You can replace iOS5 and iOS6 with any versions, for example iOS5.0 and iOS5.1)
Yes you could use your own prefix, however that is uncommon.
Yes, it can happen after an O/S update; Objective-C is a very dynamic language where messages are sent to methods rather than being called, as in other languages. These things are worked-out at runtime, not compile time.
Bottom line is yes, you might accidentally override a future base class method and the only solution is to be there when it happens and rename the method.
Prefixing your category methods are the safest way to avoid these conflicts in an every growing, non namespaced cocoa ecosystem.
It's quite valid and reasonable that framework creators, open source developers and other individual developers should prefix their class methods.
Quite often I write methods prefixed with my company initials, then continue with the method.
- (void)JCMyMethodNamedSimilarToBaseClass;
Question 1a Category
Use a prefix, or avoid the whole mess and use functions instead.
Question 1b Subclass Methods
If a method does something general enough that the superclass may also implement it, I simply choose a method name which is a little more 'wordy' than Apple would conventionally choose -- such as specifying a non standard typename in the method's name. Of course, this only reduces the possibility of collision.
If you need a higher level of security, you could just test this at execution (so you know when they are introduced) and hope every user stays up to date -- or you could rely on C and/or C++ more heavily (they do not have this problem).
Question 2
But is it possible to happen also when updating your iPhone's iOS version?
Yes. It's not so unusual. When the frameworks are updated (e.g. via software update), they may contain updated frameworks. This code is loaded into the objc runtime, and you always get the version of the installed frameworks' objc implementations.
It's also a much broader problem on OS X, where you may load code and/or plugins dynamically quite easily.
An elegant solution is to check for the method being already there and only adding it if it isn't: Conditional categories in Mountain Lion

I have made a class and that class has 100 static methods

I want to ask that i made a class which has more than 100 static methods. But class is not static, so i want to ask that do all methods live in application memory whole time or not. Or it is bad programming. please suggest me.
Please solve my issue.
Does it have any non-static method also?
if No, class should be made static.
if yes, i'll say design can be improved.
And all methods are loaded into application memory as soon as class is first used. however only one copy of methods are kept in memory.
If you really want these programs available in a reusable context, then write them as regular external C or C++ functions and add them to a library to use in other projects. Then reintroduce or wrap them as needed. I know - it's not a popular answer among objc devs, but at least it scales much better when you begin to have really complex codebases.
But class is not static, so i want to ask that do all methods live in application memory whole time or not.
Yes, and these methods may not be stripped. When you use these in other projects, you pay for everything. With functions, they may be stripped and you only pay for what you actually use in the program. Specifically, the memory of a function or method exists in the binary and in the program's memory only once - instances do not clone methods, they are referenced and looked up using a dispatch table in the runtime (like a vtable). Each instance of the class only accesses its selectors via this table so method count does not make an instance larger. Memory in this case is rarely (if ever) a concern.
Or it is bad programming. please suggest me.
This is very unusual, and an indication that something has gone wrong in the design.

Helper classes/libraries to make use of KVC/KVO on iOS more practical/safe?

This question is really looking for a specific class that I know exists, but cannot find.
A few weeks ago I read through an article outlining a helper class for using KVC - it let you encapsulate KVC subscriptions so that you could have multiple values being observed without having to go through the same hander method, and also made cleanup of the KVC observers safer (since KVC cleanup is really finicky and exception prone).
So, in responses I am looking for either that helper class I had run across before, or other examples of attempts to wrap KVC to make it safer and more palatable for general use.
I finally found what I was looking for, the key to searching was to look for examples of using KVO with blocks.
I found three interesting resources, which I'll present as a starting point - if anyone has others that are good please also answer.
The first link is the article I mentioned finding before. It has a great summary of the problems with KVO as it stands, and an interesting helper class that encapsulates a KVO session:
http://www.mikeash.com/pyblog/key-value-observing-done-right.html
The second is a simpler NSObject category that lets you pass in a block to be activated on a change notification:
http://blog.andymatuschak.org/post/156229939/kvo-blocks-block-callbacks-for-cocoa-observers
The last is another category on NSObject that uses a binding mechanism to add observation:
http://wirestorm.net/blog/2011/05/27/block-based-observation-with-kvo/
A more up-to-date implementation is facebook kvo implementation using block
It added a NSObject Category to add a KVOController property on all objects. But then we should be more careful about the retain cycles problem.

Understanding #Protocols in Objective-C

I am a beginner to programming, and a beginner to Objective-C. I learned basic C and decided to start learning Objective-C. I am reading "Programming in Objective C 2.0" by Steven Kochan.
His section on Protocols is vague. He doesn't thoroughly explain WHY someone would want to use protocols in their programs, nor does he give a concrete example with it implemented in a program.
He writes:
"You can use a protocol to define methods that you want other people who subclass your class to implement."
He also says that Protocols are good for sub-classes to be able to implement certain methods, without having to first define the actual methods. He also says protocols can be used across different classes because they are classless.
I know there must be a valid and smart way to implement protocols, but based on what he wrote, I don't see why someone would use protocols instead of just creating a class method outside of the reason that more than one class can adhere to a protocol (I know there are some more good reasons though!).
I was wondering if someone could help me understand:
how, why and when I would use Protocols in my program in an intelligent way.
If you've done any kind of object-oriented programming, you probably know protocols as interfaces (they're not identical, but the concept is similar). If not, think of protocols as blueprints.
The main reason why you'd use protocols is so you can use objects without knowing everything about them; all you need to know is that they implement a set of methods. For example, if the classes Business and Person conform to the protocol Contact, which defines the method - (NSString *)phoneNumber, the class AddressBook can call -(NSString *)phoneNumber without knowing whether or not the object is of type Business or Person.
Once you start to learn about Cocoa and delegates, you'll see how powerful and important protocols are.
One word, delegates.
Objective-c uses delegates all over the place to allow classes to talk to each other.
To see an example see UITableViewDelegate Protocol
That's not the only place #protocol is used, but it's probably the most common use for it.
Protocols are better versions of callback functions in C.
Protocols are useful constructs when you want to implement MVC architecture yourself.
The Views need to be notified when Model changes,You can use protocols to notify appropriate events to Observers.
You could have a class that is a UIViewController, and it implements several protocols, such as UITableViewDelegate, UITableViewDataSource. A class can do more than one thing.
Like #conmulligan says Objective-C uses protocols to make classes talk to each other.
Its one of many ways to communicate between classes.
But protocols is necessarily a bad way.
I use protocols if I was to create a re-usable object, that is usually used for many projects.
So I create protocols to make my code easy to maintain.