如何为视图控制器实现自定义委托方法

时间:2011-07-21 10:51:57

标签: iphone

在我的应用中有两个标签栏。在tab-0中,父类是“FirstViewController”,而在tab-1中,父类是“SecondViewController”。在“SecondViewController”中,我已经声明了协议和自定义委托方法。我想传递“FirstViewController”(FVC)中的信息。所以FVC必须被指派为代表。

现在我的疑问是,现在我在“SVC”。如何将“FVC”指定为“SVC”的代表?

在“SVC”中

[[self delegate] sendCoordinates:self];

方法的定义在“FVC”中。要执行此方法,首先我需要将“FV​​C”指定为委托。

我希望我能清楚地解释我的问题。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要设置委托。让我演示一下:

`SVC.h`

@interface SVC
{
    id _delegate;
}

- (void)setDelegate:(id)delegate; //sets the delegate
- (id)delegate; //gets the delegate

@end

@protocol SVCDelegate

- (void)sendCoordinates:(SVC *)svc;

@end

然后,在SVC.m中,您以与问题中显示的方式完全相同的方式呼叫代理,因此[[self delegate] sendCoordinates:self];

现在,在FVC中,您需要#import SVC.h并初始化对象。

SVC*svcObject = [[SVC alloc] init];
[svcObject setDelegate:self]; //self now refers to FVC - I think you're missing this one
//work with the object and when you're done, get rid of it in dealloc:
[svcObject setDelegate:nil];
[svcObject release];

在同一个类中,实现- (void)sendCoordinates:(SVC *)svc,并在设置委托后调用它。

我认为你错过了setDelegate:阶段,这就是为什么它不起作用。

希望它有所帮助!

注意:在SVC中,请记住保留委托,否则它将变为nil,并且永远不会调用任何委托方法。一旦完成,不要忘记释放该代表。

相关问题