代表 - 如何使用? [英] Delegate - How to Use?
问题描述
在我的例子中,我得到了AppDelegate创建了许多相同类型的视图(对象/视图控制器)。每个视图应该以某种方式调用AppDelegate上的一个方法来关闭它。当触摸视图中的按钮时,会发生这种情况。方法调用将包括视图(self)的引用。
到目前为止,我知道其他语言响应者,事件侦听器等。它们使用起来非常简单。
任何人都可以帮助我我刚刚在网络上发现了大量的代码。在Objective C中调用父对象不会那么难。
我认为你应该使用 NSNotificationCenter
您 AppDelegate.m
pre>
- (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
.. 。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonPushed :) name:@ButtonPushedNotificationobject:nil];
}
- (void)applicationWillTerminate :( UIApplication *)应用程序
{
...
...
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
这是在通知发生时将被调用的选择器(我们仍然是在 AppDelegate.m )
- (void)buttonPushed:(NSNotification *)notification {
NSLog(@按钮推...);
}
和 ViewController.m 当按钮推送(在方法内),您应该发布如下通知:
{
...
[[NSNotificationCenter defaultCenter] postNotificationName:@ButtonPushedNotificationobject:nil];
...
}
I think I understand the logic behind a delegate. I got more the problem to use it. How many steps are involved? Do I have to use existing delegates? Or can I use my one ones?
In my example I got the AppDelegate that created many views (Objects / View Controllers) of the same type. Each view should somehow call a method on the AppDelegate to close itself. This would happen when a button within the view is touched. The method call would include the reference of the view (self).
So far I know from other languages responders, event listeners and so on. They are so simple to use.
Can anybody help me. I just found massive examples with a lot of code in the web. It can't be that hard to just call a parent in Objective C.
I think you should use for this the NSNotificationCenter
in you 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];
}
this is the selector it will be called when the notification happens (we are still in the AppDelegate.m)
- (void)buttonPushed:(NSNotification *)notification {
NSLog(@"the button pushed...");
}
and in the ViewController.m when the button pushed (inside the method), you should post a notification like this:
{
...
[[NSNotificationCenter defaultCenter] postNotificationName:@"ButtonPushedNotification" object:nil];
...
}
这篇关于代表 - 如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!