如何从一个视图控制器访问另一个视图控制器中的对象

3

提供一些消除以下情况的提示。

描述:

我有两个视图控制器,分别是 ViewController1ViewController2,所以我们显然有 ViewController1.hViewController1.mViewController2.hViewController2.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;

如果我想将ViewController1.m中的string1值设置为ViewController2.m中的string2,我该怎么做?

3个回答

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

viewControllers是一个堆栈,所以最后被调用的那个在堆栈的顶部,而它被调用的那个则是它的父级。因此假设viewController1首先被调用,然后从其中调用了viewController2,那么你只需要在viewController2.m中执行以下操作:

[[self parentViewController] setString1:string2]

:D


0

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

如果您希望每个控制器在另一个更新字符串值时得到通知,您可以使用通知机制。这使得您的模型能够让其他对象了解其更改并独立于这些对象。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接