将委托对象类型作为协议方法参数传递

时间:2014-08-28 14:45:02

标签: ios objective-c delegates

我想将我的委托对象作为具有声明类型的参数传递,因此我不需要强制转换(如果我传递(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作为参数,但我不喜欢使用演员语法。

感谢。

注:

Apple也这样做了:

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

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

这只是UITableViewDataSource协议中的一种方法,它将UITableView类型作为参数传递。 ;)

2 个答案:

答案 0 :(得分:4)

由于这是Google搜索结果的最佳结果,所以请按以下步骤操作:

@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

答案 1 :(得分:0)

你应该这样做:

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

myObjectDelegate是您协议的名称;)

相关问题