【问题标题】:confused about delegate pattern对委托模式感到困惑
【发布时间】:2015-06-18 17:21:10
【问题描述】:

我正在从 Nib 创建自定义 UIView 子类 (shareView)。 我为 shareView 创建了一个自定义协议,如下所示:

@protocol sharePopupDelegate
@required

-(void)userPublishedContent;
-(void)userAbortedPublish;

@end

@interface shareView : UIView
{
     id<sharePopupDelegate> delegate;
}    

在我的 main.storyboard 中,我创建了一个自定义 UIViewController myViewController,其中包含一个名为“popup”的 shareView 视图实例。

所以现在我得到了

@property (weak, nonatomic) IBOutlet shareView *popup;

我现在想从我声明的 shareView 方法中委托 myViewController,所以我这样做了

self.popup.delegate = self;

在 myViewController 内部,但协议的方法并未在 myViewController 内部调用。

所以我正确地看到了 shareView 实例,但无法与其委托交互。

你能帮帮我吗?

提前致谢

【问题讨论】:

  • 首先,不要这样做 id 委托;使其成为弱属性。请发布 shareView 在其委托上执行委托方法时的代码。我正在寻找这样的东西:[self.delegate userPublishedContent];

标签: ios objective-c delegates storyboard subclass


【解决方案1】:

确保在 myViewController 中声明了协议。

例如

   @interface MyViewController : UIViewCOntroller <sharePopupDelegate>

【讨论】:

    【解决方案2】:

    在这部分代码中:

    @interface shareView : UIView
    {
         id<sharePopupDelegate> delegate;
    }   
    

    您正在创建对委托的强引用,这在大多数情况下都不是您想要的。改成这样:

    @interface shareView : UIView
    @property(weak, nonatomic) id<sharePopupDelegate> delegate;
    

    shareView 类本身必须有某种方式知道用户何时发布内容。也许您有一个链接到 shareView 的操作,该操作调用 shareView 类中的方法。例如:

    - (void)publishButtonTapped {
    // some code
    }
    

    您要做的是让代理知道该方法,如下所示:

    - (void)publishButtonTapped {
    
    // some code
    [self.delegate userPublishedContent];
    }
    

    然后用户采取的任何取消操作:

    - (void)cancelButtonTapped {
    
    // some code
    [self.delegate userAbortedPublish];
    }
    

    希望这会有所帮助。

    【讨论】:

    • 我试过但不幸的是没有解决,我认为问题在于:“self.popup.delegate = self”。一种应该禁止的委托协议的自我分配,但不知道如何解决
    • 我不认为那部分是问题,显示shareView .m 的代码。如果您没有 [self.delegate userPublishedContent],那可能就是问题所在。如果你这样做了,设置一个断点,看看它是否被命中。
    猜你喜欢
    • 1970-01-01
    • 2014-11-27
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2022-01-04
    相关资源
    最近更新 更多