ios - 委托(delegate)方法发送自己的对象或不发送它

标签 ios objective-c delegates protocols nsobject

我用过@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定义?

最后一个,最好创建@ propertyassignstrong

谢谢

最佳答案

通常,您传递给委托(delegate)的对象可以被使用,这样同一个委托(delegate)类就可以在不同的上下文中使用。在委托(delegate)类可能被重用的情况下,这为您提供了更大的灵 active 。

例如,如果 showAndHideCommentView 需要与显示或隐藏的 View 进行交互,它有两种实现方式:

  1. 获取 View 作为参数,或者
  2. 直接引用 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/

相关文章:

iOS:此方法适用于 iOS 设备吗?

ios - 如何在 iOS SDK 3.0 上检查和更新 Facebook token 的状态?

uicollectionview - 我如何知道 UICollectionView 已完全加载?

ios - SWIFT 中的应用内购买 - 未调用 productsRequest 委托(delegate)

ios - 如何在我的 iOS 应用程序上接收短信(解决方法)?

ios - UITileLayer 显示忽略伪造的图层大小

ios - 应用程序 :openURL:sourceApplication:annotation: is not getting called in iOS8

ios - 重新加载 UITableView

php - 如何在 NSDictionary 中 POST NSArray of NSDictionaries 而没有问题?

c# - 在构造函数中委托(delegate)调用