objective-c - 委托(delegate) - 如何使用?

标签 objective-c ios delegates

我想我理解委托(delegate)背后的逻辑。我有更多使用它的问题。涉及多少步骤?我必须使用现有的委托(delegate)吗?或者我可以使用我的一个吗?

在我的示例中,我得到了创建许多相同类型的 View (对象/ View Controller )的 AppDelegate。每个 View 都应该以某种方式调用 AppDelegate 上的方法来关闭自己。当触摸 View 中的按钮时会发生这种情况。方法调用将包括 View (自身)的引用。

到目前为止,我从其他语言的响应者、事件监听器等处了解到。它们使用起来非常简单。

有谁能够帮助我。我刚刚在网上找到了包含大量代码的大量示例。在 Objective C 中调用父级并不难。

最佳答案

我认为您应该为此使用 NSNotificationCenter
在你 AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
...
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonPushed:) name:@"ButtonPushedNotification" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
...
...
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

这是通知发生时将调用的选择器(我们仍在 AppDelegate.m 中)
- (void)buttonPushed:(NSNotification *)notification {
NSLog(@"the button pushed...");
}

ViewController.m 当按下按钮时(在方法内部),您应该发布这样的通知:
{
...
[[NSNotificationCenter defaultCenter] postNotificationName:@"ButtonPushedNotification" object:nil];
...
}

关于objective-c - 委托(delegate) - 如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11229830/

相关文章:

c# - 如何创建一个通用包装方法来返回包装方法的结果(如果有)?

javascript - 使用 jquery .delegate 未调用函数

ios - 让 UIImage 从 JSON 工作

iphone - Core Data 托管对象的生命周期

ios - 推送通知更改 AppIcon 的角标(Badge)

iphone - 未调用委托(delegate)方法 "clickedButtonAtIndex:"

ios - 为什么我不必在 Swift 中使用 NSBundle 之前导入 Foundation?

ios - UIStoryboard 中的场景截图

ios - Swift Table View Cell 布局折叠所有元素

c# - 与多个事件发布者和多线程关联的单个 .NET 事件订阅者