Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C call hidden methods

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.

like image 293
Kami Avatar asked Mar 23 '26 20:03

Kami


2 Answers

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.)

like image 87
Ole Begemann Avatar answered Mar 25 '26 12:03

Ole Begemann


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
like image 38
Stephen Furlani Avatar answered Mar 25 '26 11:03

Stephen Furlani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!