2008-12-28 155 views
4

定義如何創建一個類的@implementation的方法,而不在@interface定義它?創建的實現方法沒有頭

例如,我有一個構造函數,做一些初始化,然後從文件中讀取數據。我想將文件讀取代碼分解爲一個單獨的方法,然後在構造函數中調用它。我不想在頭文件來定義這種方法,因爲它是公開的,只有這@implementation上下文。

這可能嗎?

這是我的例子。我有一個小程序,它是從文件中讀取Todo任務列表的。

這裏是@interface:

@interface TDTaskList : NSObject { 
    NSString* name; // The name of this list. 
    NSMutableArray* tasks; // The set of tasks in this list. 
} 

-(id)initListOfName:(NSString*)aName; 
-(NSArray*)loadListWithName:(NSString*)aName; 

@end 

這裏是@implementation的一部分:

-(id)initListOfName:(NSString*)aName { 
    if (self = [super init]) { 
    name = aName; 

    NSArray* aTasks = [self loadListWithName:aName]; 
    tasks = [NSMutableArray arrayWithArray:aTasks]; 
    } 

    return self; 
} 

-(NSArray*)loadListWithName:(NSString*)aName { 
    // TODO This is a STUB till i figure out how to read/write from a file ... 

    TDTask* task1 = [[TDTask alloc] initWithLabel:@"Get the Milk."]; 
    TDTask* task2 = [[TDTask alloc] initWithLabel:@"Do some homework."]; 

    return [NSArray arrayWithObjects:task1, task2, nil]; 
} 

我想要做的是已經確定在以下接口:

-(NSArray*)loadListWithName:(NSString*)aName; 

回答

10

如果你把一個方法的實現調用了它,你不需要在標題中定義的任何代碼之前。

因此,在這種情況下,把loadListWithName:initListOfName面前:在@implementation塊,這將是很好的。

注意:僅僅因爲它沒有在頭文件中定義,並不意味着該方法不能被對象之外的代碼調用。 Objective-C沒有私有方法。

+1

這是正確的答案。 – mxcl 2009-06-23 16:29:56

2

您可以使用categories

// In TDTaskList.m 
@interface TDTaskList(TDTaskListPrivate) 
-(id)initListOfName:(NSString*)aName; 
-(NSArray*)loadListWithName:(NSString*)aName; 
@end 

@implementation TDTaskList(TDTaskListPrivate) 

// implementation of initListOfName and loadListWithName ... 

@end 
+0

注意,作爲目標C 2.0的CA的私人類別不再需要名稱名稱。這有助於保持代碼更簡單。 – Andy 2008-12-28 02:15:40

6

安迪在評論中暗示,你可以使用Extensions(這看起來像一個類別沒有名字)。所不同的是,你必須實現在擴展聲明的方法,而編譯器不會驗證您實現在一個類別聲明的方法。

.H:

@interface MyObject : NSObject 
{ 
    NSNumber *number; 
} 
- (NSNumber *)number; 
@end 

.M:

@interface MyObject() 
- (void)setNumber:(NSNumber *)newNumber; 
@end 

@implementation MyObject 

- (NSNumber *)number 
{ 
    return number; 
} 
- (void)setNumber:(NSNumber *)newNumber 
{ 
    number = newNumber; 
} 
@end 
1

你有兩個合理的選擇。兩者基本上都已經被描述過了,但是恕我直言有些不清楚,甚至是明顯的錯誤。

類別不是其中之一,因爲它們是AFAIK意思是將實現分解爲多個源文件的完全不同的目的。

  • 做上述彌敦道。雖然他最後的假設(私人方法)是錯誤的。
  • 使用一個私有方法擴展定義,以允許正向引用如下:

    1. 從頭部移除loadListWithName的定義完全
    2. 的@implementation塊
    3. 之前添加以下到源(.M)
     
    @interface TDTaskList (PrivateMethods) 
    -(NSArray*)loadListWithName:(NSString*)aName; 
    @end 
    
    @implementation ... 
    

  • 相關問題