2014-08-28 101 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