tags:

views:

37

answers:

2

I am trying to improve the design of my App by using private methods. Coming from .NET I am a little confused because I am declaring these methods in the .m file but from other files they are still showing up i.e. they are still accessible.

.m file:

@interface NSContentWebServiceController (private)

- (NSString *)flattenHTML:(NSString *)html;
- (NSString *)cleanseStringOfJsonP:(NSString *)jsonP;
- (void)retrieve:(NSasdf *)hasdel :(NSDictionary *)rootList;   
- (NSString *)removeHTMLTagsFromString:(NSString *)aString;

@end
+1  A: 

Private methods are only private in a way that they're not documented in a header file. Because of this you can't #import them into your project and thus will the compiler warn you about a 'selector not recognized' or something like that.

You'll be able to call these methods just as public methods, since it's just where you declare the prototype that makes a method private, Objective-C doesn't have such a thing as hidden, really private, methods.

At runtime, you will always be able to find all methods using introspection, so there really is no way of completely hiding your methods/properties.

You could add a id _internal instance variable which points to an object that does all the work, that way it's a bit more tough to call the private methods, although not impossible.

JoostK
Thanks JoostK - I was finding conflicting information online - don't think people understand it.
TheLearner
Just out of interest - what does Apple recommend? Like I have done it or everything in the .h file?
TheLearner
I don't know really. I always use the way you do it, but name my methods starting with an underscore `_`. That way I'm able to easily identify whether a method is private or not.
JoostK
+2  A: 

As JoostK said, there are no private methods in Objective-C like you have them in C++, Java or C#.

On top of that, the expression @interface NSContentWebServiceController (private) defines a so-called category in Objective-C. The term private here is merely a name for the category and has no meaning. Having something like yellowBunny in here would yield the same effect. A category is merely a way to break down a class into several pieces, but at runtime all categories are in effect. Note that a category is only able to add new methods to an object class, but not new variables.

For private categories it's now preferred to use the anonymous category, as in @interface MyClass(), as you then don't need a separate @implementation MyClass(yellowBunny) block but can just add the methods to main @implementation block.

See the "Categories" section in the Wikipedia entry on Objective-C for more information.

DarkDust