代表 - 如何使用? [英] Delegate - How to Use?

查看:98
本文介绍了代表 - 如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我理解代表背后的逻辑。我有更多的问题来使用它。涉及多少步?我必须使用现有的代表吗?或者我可以使用我的一个?



在我的例子中,我得到了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆