开发者

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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜