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

时间:2009-04-01 08:06:41

标签: objective-c

提供一些提示,以摆脱以下情况。

说明

我有两个viewControllers,即 ViewController1 ViewController2 ,所以我们有 ViewController1.h ViewController1.m ViewController2.h ViewController2.m 。 现在我宣布了一个

NSString *string1;
ViewController1.h

并将其声明为属性

@property(nonatomic,retain) NSString *string1;

并在 ViewController1.m 中将其合成为

@synthesize string1;

并在 ViewController1.m 中,我将string1值设置为

string1=@"Hello Every One";

同样我声明了

NSString *string2;
ViewController2.h

并将其声明为属性

@property(nonatomic,retain)NSString *string2;

并在 ViewController2.m 中将其合成为

@synthesize string2;

如果我想将string1值(在 ViewController1.m 中)设置为string2(在 ViewController2.m 中),我该怎么办?那样做?

3 个答案:

答案 0 :(得分:3)

这取决于您要在哪里运行设置string1的代码。如果它在一些可以访问两个视图控制器对象的外部类中,那么它很简单。如果您有ViewController1对象vc1和ViewController2对象vc2,那么您所做的就是:

[vc1 setString1:[vc2 string2]];

如果要在ViewController2中运行代码中设置string1,则使用通知机制。在ViewController1的初始化例程中,您输入:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aChangeStringMethod:) name:@"anyStringJustMakeItUnique" object:nil];

并定义:

-(void)aChangeStringMethod:(NSNotification)notification{
     string1 = [((ViewController2 *)[notification object]) string2];
}

然后,在ViewController2中,当您想要更改字符串时:

[[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]];

答案 1 :(得分:1)

viewControllers是一个堆栈,所以最后一个调用的是堆栈顶部,而它调用的那个是它的父级。因此,假设首先调用viewController1,然后从内部调用viewController2,那么viewController2.m中的所有内容都是:

[[self parentViewController] setString1:string2]

:d

答案 2 :(得分:0)

您可以使用包含两个字符串且两个控制器都知道的模型对象。

如果您希望每当控制器更新字符串的值时通知每个控制器,您可以使用notification mechanism。这允许您的模型让其他对象了解其更改并与这些对象保持独立。