我正在通过委托(delegate)和协议(protocol)传递一个字符串。字符串已正确接收到类,但这发生在调用 viewDidLoad 方法之后。 viewDidLoad 方法需要传递该字符串。
关于如何在 viewDidLoad 之前调用委托(delegate)方法有什么想法吗?我认为这就是委托(delegate)/协议(protocol)数据传递的想法。
创建和推送新 View 的方法:
ViewControllerTwo *two = [[ViewControllerTwo alloc] initWithNibName:@"ViewControllerTwo" bundle:nil];
two.delegate = self;
[two setString:theString];
[self.navigationController pushViewController:two animated:YES];
[two release];
在 ViewControllerTwo 中:
- (void)setString:(NSString *)str
{
self.myString = str;
}
编辑:感谢您的意见。不过,我确实了解如何通过 init 方法传递这些数据。我最近一直在测试协议(protocol)和代表,我想看看是否有办法做到这一点。我已经在另一个类(class)成功地传递了这样的数据并且它有效。首先调用协议(protocol)方法来设置字符串。这似乎是一种更干净的处理传递数据的方法。
最佳答案
我认为您可能对委托(delegate)
的用途和原因有些困惑。
例如,如果您在该 ViewController
中执行某种操作并且需要通知另一个子类该操作,您可能希望在 UIViewController
子类中制定协议(protocol)正在采取的行动,或该行动的结果。
现在,为了让子类想要了解操作(接收者),它必须遵守其头文件中的协议(protocol)。
您还必须将委托(delegate)
“设置”到接收类/ Controller
。
有很多方法可以获取对接收 Controller /类
的引用,并将其设置为委托(delegate)
,但一个常见的错误是分配和初始化该实例的新实例当该类已经创建时,将其设置为委托(delegate)。这样做的目的是将新创建的类设置为委托(delegate),而不是已创建并等待消息的类。
您想要做的只是将值传递给新创建的类。由于您刚刚创建了这个 UIViewController
类,因此所需的只是 receiver(ViewControllerTwo)
中的一个属性。
在您的情况下,NSString
:
@Property (nonatiomic, retain) NSString *string; //goes in ViewControllerTwo.h
当然不要忘记主要内容:
@synthesize string; //Goes in ViewControllerTwo.m
现在,您的 ViewControllerTwo
中不再需要 setter 。
- (void)setString:(NSString *)str //This Method can be erased
{ //The setter is created for free
self.myString = str; // when you synthesized the property
}
当您使用@synthesize
时,setter 和 Getter 是免费的。只需将值传递给 ViewController
即可。除了委托(delegate)之外,实现与您的代码相同:
ViewControllerTwo *two = [[ViewControllerTwo alloc] initWithNibName:@"ViewControllerTwo" bundle:nil];
[two setString:theString];
[self.navigationController pushViewController:two animated:YES];
[two release];
关于iPhone 协议(protocol)委托(delegate)传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9812808/