2009-12-30 59 views
0

我有一個問題,我解決了使用代表,但現在我想我可能犯了一個錯誤。代表和多種方法

這就是我想要做的。

我有一個延遲運行的類。完成後,它將完成它所調用的委託。

現在我有創建這些延遲類中的兩個的主類。

我不希望他們都在主類相同isfinished方法進行處理。我想用兩種不同的。

但是我相信,創造代表,這不會爲我工作的協議方法。

有沒有辦法解決這個問題?

delayclass setdelegates MainclassFunction1 
delayclass setdelegates MainclassFunction2 

回答

1

使用委託對我來說似乎不是正確的方法;他們通常用於增強行爲。這裏最適合的是目標/選擇器模式,如NSTimer。

@interface MyObject : NSObject { 
@private 
    id target; 
    SEL selector; 
} 
@property(assign) id target; 
@property SEL selector; /* The selector must return void and accept one argument, which is the MyObject instance that invoked the method. */ 
@end 

@implementation MyObject 
- (void)notifyTarget { 
    [[self target] performSelector:[self selector] withObject:self]; 
} 
@synthesize target; 
@synthesize selector; 
@end 

這通常是因爲委託回調並不需要澄清對發送者最乾淨的方法。對於此域中的問題,使用通知看起來太多了。

+0

正是我需要的。謝謝! – Mel 2010-01-02 18:00:00

5

如果我理解正確的話,看看在NSTableViewDelegate協議。在那裏,每個委託方法的第一個參數是發送消息的NSTableView實例。

您可以通過更改您的委託方法讓你的委託對象發送自身作爲參數傳入解決您的問題。然後,在您的代理,你會做這樣的事情:

if (theDelegator == objectA) 
{ 
    // Do something 
} 

if (theDelegator == objectB) 
{ 
    // Do something else 
} 

這樣,你有一個可以處理多個對象委託給它乾淨實現的委託方法。

1

如前所述,常用的委託方法將包括髮起回調的對象,這樣你就可以區分這種方式。或者,您可以讓對象發佈通知,而這也會使發件人可用。

0

你爲什麼不只是使用的NSTimer,加入不同的定時器,並讓他們給你打電話你正在使用像現在委託類喜歡什麼選擇?

喜歡的東西:

NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(myMethod1:) userInfo:nil repeats:YES]; 

NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(myMethod2:) userInfo:nil repeats:YES]; 

如果你的方法是:

- (void) myMethod1:(NSTimer*)theTimer 
{ 
    // do Something 
} 

- (void) myMethod2:(NSTimer*)theTimer 
{ 
    // do Something different 
} 

要保存關閉,同時保留定時器1 /定時器2的引用,這樣就可以停止的dealloc定時器([timer1 invalidate] )。

+0

實際示例要複雜得多,我只想抽象它 – Mel 2009-12-31 01:53:50

0

短注:一般情況下,這是不好的風格有「如果」某個對象的switch語句。我們都偶爾會得到第二個不需要新控制器的列表,但切換是在內部進行的方法調用,所以理想情況下,您只需讓ObjC運行時間負責做正確的事情。有幾個選項:

-(void) tableViewSelectionDidChange: (NSTableView*)theView 
{ 
    SEL theAction = NSSelectorFromString([NSString stringWithFormat: @"tableView%@SelectionDidChange:", [theView autosaveName]]); 
    [self performSelector: theAction withObject: theView]; 
} 

-(void) tableViewUKSourceListSelectionDidChange: (NSTableView*)theView 
{ 
    // UKSourceList-table-specific stuff here. 
} 


-(void) tableViewUKUsersListSelectionDidChange: (NSTableView*)theView 
{ 
    // UKUsersList-table-specific stuff here. 
} 

這工作時,你最好有一個非本地化字符串標籤,如自動保存的名稱,但也可以使用標籤,儘管這使代碼的可讀性(其中一個是「表1」 ?)。有時最好只寫一個具有特殊字符串的子類,或者甚至有方法可以指定選擇器名稱來轉發委託方法。

Caleb的建議也不錯,如果您想要谷歌的話,它也被稱爲「目標/行動」。我有幾個(Mac)類,它們具有點擊的常規「動作」,雙點擊的「雙動」等。