我想我理解委托(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/