Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private interface vs. private method - objective c

What is the difference between a private method and a private interface? For example, I know that if you define a method in an implementation and its interface does not mention it, it is considered a private method. I have also seen things such as:

@interface Collector()
@property (readonly) NSMutableDictionary *count;
@end

Inside of the .m implementation file.

like image 609
joshim5 Avatar asked Oct 15 '10 16:10

joshim5


1 Answers

@interface Foo() creates a class extension (I stand corrected, props to bbum) on interface Foo which is like additional methods added to the interface. Some people also use @interafce Foo(Private) (category) instead of a class extension with (). It's more like "injecting" new methods into a class from outside the class.

Placing this in the .m file just keeps other things from "seeing it" in the .h file, but that's it. Basically people normally use categories or class extensions in .m files to specify private interfaces, but they are also used for things like UIKit uses categories to add row and section public methods to NSIndexPath. (This can be confusing.)

You don't really need to define private methods this way, but if you have a method called bar that calls method foo before foo is defined in the source file you'll get a compiler warning something like "object self may not respond to foo". You can get rid of that by defining foo before you define bar or any other foo-calling code. It's the same with plain C and functions.

Like Ole says this doesn't stop anyone from calling the private methods, it just declares your intention that they be private and causes the compiler to generate the "may not respond to" warnings even if they import the .h file.

EDIT

Also see http://www.friday.com/bbum/2009/09/11/class-extensions-explained/ for some explanation of categories vs. class extensions. Looks like class extensions should be more correct for defining private methods, from a compiler warning perspective, because category methods are optional. Wish my book would have explained this!

like image 119
Nimrod Avatar answered Sep 18 '22 09:09

Nimrod