2014-08-28 102 views
1

我想通過我的委託對象爲具有聲明類型的參數,所以我沒有投(如果我通過(ID),發件人,而不是):通委託對象類型作爲協議的方法參數

@protocol myObjectDelegate <NSObject> 
- (void)myObjectAsArgument:(myObject *)object; 
@end 

@interface myObject : NSObject 
    // stuff... 
    @property (nonatomic, strong) id <myObjectDelegate> delegate; 
@end 

這樣做的正確方法是什麼?就像我說的,我知道我能做到這一點:

- (void)myObjectAsArgument:(id)object; 

這將讓我在作爲參數傳遞self,但我不喜歡使用CAST語法。

謝謝。

注:

蘋果確實太:

@protocol UITableViewDataSource <NSObject> 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; 
@end 

@interface UITableView : UIScrollView 
@property (nonatomic, strong) id <UITableViewDataSource> dataSource; 
@end 

這是從UITableViewDataSource協議只是一個方法,它的傳遞一個UITableView類型作爲參數。 ;)

回答

4

因爲這是頂級谷歌的搜索結果,這裏是如何做到這一點:

@class myObject; // just need this for compiling 

@protocol myObjectDelegate <NSObject> 
- (void)myObjectAsArgument:(myObject *)object; 
@end 

@interface myObject : NSObject 
    // stuff... 
@property (nonatomic, strong) id <myObjectDelegate> delegate; 
@end 
+0

我不認爲哪個是一個好主意,在哪裏保持一個委託的強大參考。 – Goppinath 2014-08-29 06:08:41

+0

代表引用應該總是很強大,因爲你可以,所以它在蘋果的文檔 – believesInSanta 2014-08-29 06:56:23

+0

中,並不意味着你應該,在這種情況下,沒有什麼可以說你不能做。基本上是如果我想保留我的對象在內存中,直到我的委託所有者和我的委託對象被髮送垃圾回收?爲什麼不? – believesInSanta 2014-08-29 07:04:23

0

你應該做的是這樣的:

- (void)myObjectAsArgument:(id<myObjectDelegate>)object; 

myObjectDelegate是您的協議的名稱;)

+0

嘿,那會傳遞委託對象作爲參數,我在我的界面聲明中添加了一行代碼。 – believesInSanta 2014-08-28 15:29:55

+0

實質上,它是我想要通過 – believesInSanta 2014-08-28 15:39:37

+0

的代理程序ING對象。我不知道人們會喜歡這樣做:DI認爲做你正在做的事情的唯一方法是將你的類型硬編碼到你的協議中,使用子類或創建第二個協議 – 2014-08-28 15:53:17