PDA

View Full Version : Is there any similiar to a private method in Objective-C?




fenrus110
Apr 13, 2008, 12:36 PM
I want to just write a simple helper method, but I don't want to expose it to the public interface (since that breaks encapsulation and what not).

Does Objective-C support anything like this?

Like if I write this
NSString *s = [self helper:txtFirst.text];
s = [self helper:txtLast.text];

Obviously, I'll get a compile error if I haven't declared "helper" in the header file. Is there any way around this?



kainjow
Apr 13, 2008, 12:40 PM
Just declare helper: in the .m file before @implementation, like so:

@interface YourClass (PrivateMethods)
- (NSString *)helper:(NSString *)arg;
@end

Then you can call it all you want but only the code in your .m can see it.

Eraserhead
Apr 13, 2008, 12:50 PM
Nice tip, I didn't realise you could do that.

fenrus110
Apr 13, 2008, 12:55 PM
thanks

robbieduncan
Apr 13, 2008, 01:16 PM
Note that unlike Java this doesn't actually prevent other objects accessing these methods. You'll get the normal warning about methods not existing when you compile, but it'll work at runtime.

Krevnik
Apr 13, 2008, 02:05 PM
Note that unlike Java this doesn't actually prevent other objects accessing these methods. You'll get the normal warning about methods not existing when you compile, but it'll work at runtime.

Yes, the problem is that the Obj-C runtime doesn't offer the protections during execution, as it doesn't know what is private and what isn't when it comes to methods.

But, for the sake of most development, the distinction of public/private isn't to actually protect code, but act as enforcement for good code policy, and help make it clear what can and shouldn't be used in APIs. Categories are sufficient for this purpose.