Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

fenrus110

macrumors regular
Original poster
Mar 24, 2008
142
0
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

Moderator emeritus
Jun 15, 2000
7,958
7
Just declare helper: in the .m file before @implementation, like so:

Code:
@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.
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
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

macrumors 601
Sep 8, 2003
4,101
1,312
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.