Is there any similiar to a private method in Objective-C?

Discussion in 'Mac Programming' started by fenrus110, Apr 13, 2008.

  1. fenrus110
    Expand Collapse
    macrumors regular

    Joined:
    Mar 24, 2008
    #1
    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?
     
  2. kainjow
    Expand Collapse
    Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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.
     
  3. Eraserhead
    Expand Collapse
    macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #3
    Nice tip, I didn't realise you could do that.
     
  4. fenrus110
    Expand Collapse
    thread starter macrumors regular

    Joined:
    Mar 24, 2008
  5. robbieduncan
    Expand Collapse
    Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    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.
     
  6. Krevnik
    Expand Collapse
    macrumors 68030

    Krevnik

    Joined:
    Sep 8, 2003
    #6
    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.
     

Share This Page