我用过@protocols
很多次,但我认为我一直做错了。他们一直都很好,但现在我想提高自己的水平,所以我会努力做得更好。
我总是这样创建一个委托(delegate):
@protocol CommentViewDelegate;
@interface LZCommentView : UIView
@property (assign, nonatomic) id <CommentViewDelegate> delegate;
@end
@protocol CommentViewDelegate
-(void)showAndHideCommentView;
@end
现在,我看到几乎所有我看到的委托(delegate)方法都发送它们自己的对象。像这样:
-(void)showAndHideCommentView:(LZCommentView *)commentView;
我做的和这个有什么区别?其中一个比另一个更好吗?我看到几乎每个这样做的人都不使用 ViewController
中的对象.
另一个问题是,我应该使用 <NSObject>
吗?在@protocol
定义?
最后一个,最好创建@ property
与 assign
或 strong
?
谢谢
最佳答案
通常,您传递给委托(delegate)的对象可以被使用,这样同一个委托(delegate)类就可以在不同的上下文中使用。在委托(delegate)类可能被重用的情况下,这为您提供了更大的灵 active 。
例如,如果 showAndHideCommentView
需要与显示或隐藏的 View 进行交互,它有两种实现方式:
- 获取 View 作为参数,或者
- 直接引用 View ,知道该委托(delegate)附加到特定 View 。
第一种方法的例子:
@implementation MyDelegate
-(void)showAndHideCommentView:(LZCommentView *)commentView {
if (isShowing) {
[commentView doSomething];
}
}
@end
第二种方法的例子:
@implementation MyDelegate
-(void)showAndHideCommentView {
if (isShowing) {
[self.commentView doSomething];
}
}
@end
第一种方法比第二种方法更灵活,因为它允许您重用相同的代码。
根据 Apple,it’s best practice to define your protocols to conform to the NSObject
protocol ,所以你的第二个问题的答案是"is"。
就第三个问题而言,声明委托(delegate)属性的最佳方式是使用 weak
属性以避免保留循环。
关于ios - 委托(delegate)方法发送自己的对象或不发送它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22394660/