2

The following is an example of hidden method in Objective-C:

MyClass.m

#import "MyClass.h"

 
@interface MyClass (Private)
   -(void) privateMethod:(NSString *)arg1 and: (NSString*)arg2;
@end

@implementation MyClass

   -(void) publicMethod {
       NSLog(@"public method\n");
      /*call privateMethod with arg1, and arg2 ??? */
   }

   -(void) privateMethod:(NSString *)arg1 and: (NSString*)arg2{
       NSLog(@"Arg1 %@ and Arg2 %@", arg1, arg2);
   }

@end

I've read about private interface / methods declaration. But how to invoke them from an other public method ? I've tried [self privateMethod:@"Foo" and: @"Bar"] but it doesn't looks right.

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
Kami
  • 5,959
  • 8
  • 38
  • 51

2 Answers2

8

Yes, [self privateMethod:@"Foo" and:@"Bar"] is correct. What looks wrong about it? And why didn't you just try it?

(Btw, it's not really a private method, it's just hidden from the interface. Any outside object that knows the message signature can still call it. "Real" private methods don't exist in Objective-C.)

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Actually I've tried it and it crashes. So if all of you say it's right, it might come from an other place. – Kami Jan 25 '11 at 13:30
  • 2
    Actually you can simulate private methods through an "empty" category. For farther discussions look [here](http://stackoverflow.com/questions/172598/best-way-to-define-private-methods-for-a-class-in-objective-c) – Martin Babacaev Jan 25 '11 at 14:11
  • But I still get a warning for doing this (MyClass may not responds to privateMethod), is this ok? I feel like this isn't right... – Enrico Susatyo Feb 04 '11 at 04:12
2

Try the following. "Private" interfaces should be declared with no category in the ().

MyClass.h

@interface MyClass : NSObject
   -(void) publicMethod;
@property int publicInt;
@end

MyClass.m

#import "MyClass.h"

@interface MyClass ()
   -(void) privateMethod:(NSString *)arg1 and: (NSString*)arg2;
@property float privateFloat;
@end

@implementation MyClass

@synthesize publicInt = _Int;
@synthesize privateFloat = _pFloat;

   -(void) publicMethod {
      NSLog(@"public method\n");
      /*call privateMethod with arg1, and arg2 ??? */
      [self privateMethod:@"foo" and: @"bar"];
   }

   -(void) privateMethod:(NSString *)arg1 and: (NSString*)arg2{
       NSLog(@"Arg1 %@ and Arg2 %@", arg1, arg2);
   }

@end
Stephen Furlani
  • 6,794
  • 4
  • 31
  • 60