Objective-C调用私有方法

时间:2011-01-25 13:24:55

标签: objective-c class-design private-methods

以下是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

我读过有关私有接口/方法声明的内容。但是如何从其他公共方法调用它们? 我试过了[self privateMethod:@"Foo" and: @"Bar"],但看起来不对。

2 个答案:

答案 0 :(得分:8)

是的,[self privateMethod:@"Foo" and:@"Bar"]是正确的。它看起来有什么问题?你为什么不试试呢?

(顺便说一句,它不是真正的私有方法,它只是从界面隐藏。任何知道消息签名的外部对象仍然可以调用它。“Objective-C中不存在真正的”私有方法。“

答案 1 :(得分:2)

尝试以下方法。应在()

中声明“私有”接口没有类别

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