这取决于您要在其中设置 string1 的代码的运行位置。如果它位于某个可以访问两个视图控制器对象的外部类中,那么就很简单。如果你有 ViewController1 对象 vc1 和 ViewController2 对象 vc2,那么你要做的就是:
[vc1 setString1:[vc2 string2]];
如果您想从 ViewController 2 中运行的代码设置 string1,则可以使用通知机制。在 ViewController 1 的初始化例程中,您输入:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aChangeStringMethod:) name:@"anyStringJustMakeItUnique" object:nil];
并定义:
-(void)aChangeStringMethod:(NSNotification)notification{
string1 = [((ViewController2 *)[notification object]) string2];
}
然后,在 ViewController 中,当您想要更改字符串时:
[[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:self];
当您从可以访问 vc2 但不能访问 vc1 的某个第三类更改字符串时,可以使用相同的技术。 ViewController1代码与上面相同,当你想改变字符串时:
[[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:vc2];
最棘手的部分是如果您想从 ViewController1 中更改字符串(假设您无权访问对象 vc2)。您必须使用两个通知:上面的一个,以及 ViewController2 的通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(launchTheOtherNotificationMethod:) name:@"anotherNotificationName" object:nil];
-(void)launchTheOtherNotificationMethod:(NSNotification)notification{
[[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:self];
}
然后,当你想更改字符串时:
[[NSNotificationCenter defaultCenter] postNotificationName:@"anotherNotificationName" withObject:nil];
如果您认为这太复杂或导致太多开销,更简单的解决方案是像 ViewController1 和 ViewController2 中的字段一样,使用指向彼此的指针。然后,在 ViewController1 中:
string1 = [myVC2 string2];
如果您将这些字段设置为属性,那么从外部:
[vc1 setString1:[[vc1 myVC2] string2]];
乃至:
[[vc2 myVC1] setString1:[vc2 string2]];