如何从一个 ViewController 到另一个 ViewController 访问对象

2024-06-03

提供一些技巧来摆脱以下情况。

描述:

我有两个 viewController,即视图控制器1 and 视图控制器2,所以显然我们有ViewController1.h, ViewController1.m and ViewController2.h, ViewController2.m。 现在我宣布

NSString *string1;

in ViewController1.h并将其声明为财产

@property(nonatomic,retain) NSString *string1;

并将其合成于ViewController1.m as

@synthesize string1;

and in ViewController1.m,我将 string1 值设置为

string1=@"Hello Every One";

同样我声明

NSString *string2;

in ViewController2.h并将其声明为财产

@property(nonatomic,retain)NSString *string2;

并将其合成于ViewController2.m as

@synthesize string2;

如果我想设置string1值(在ViewController1.m) to string2 (in ViewController2.m), 我怎样才能做到这一点?


这取决于您要在其中设置 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]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从一个 ViewController 到另一个 ViewController 访问对象 的相关文章

随机推荐