2011-01-25 142 views
1

以下是在Objective-C私有方法的一个示例:Objective-C的呼叫私有方法

#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 

我读过有关专用接口/方法声明

MyClass.m。但如何从其他公共方法调用它们? 我试过[self privateMethod:@"Foo" and: @"Bar"],但它看起来不正确。

+0

看起来我的权利。 – badgerr 2011-01-25 13:26:56

回答

8

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

(顺便说一下,这是不是一个真正的私有方法,它只是隐藏在接口才会知道消息签名任何外部对象仍然可以称之为“真正的”私有方法不Objective-C的存在。)

+0

其实我试过了,它崩溃了。所以如果你们所有人都说这是对的,它可能来自其他地方。 – Kami 2011-01-25 13:30:03

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