2011-01-25 144 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