How to access objects from one ViewController to another ViewController

Provide some tips to get rid of the following scenario.

Description:

I have two viewControllers, namely ViewController1 and ViewController2, so, oddly enough, we have ViewController1.h, ViewController1.m and ViewController2.h, ViewController2.m. Now i announced

NSString *string1;

in ViewController1.h and declared it as a property

@property(nonatomic,retain) NSString *string1;

and synthesized it in ViewController1.m as

@synthesize string1;

and in ViewController1.m, I set the value of string1 as

string1=@"Hello Every One";

Similarly, I announced

NSString *string2;

in ViewController2.h and declared it as a property

@property(nonatomic,retain)NSString *string2;

and synthesized it in ViewController2.m as

@synthesize string2;

If I want to set the value string1(in ViewController1.m) to string2(in ViewController2.m), how can I do this?

+3
3

, , string1 in. - , . ViewController1 vc1 ViewController2 vc2, , , :

[vc1 setString1:[vc2 string2]];

string1 , ViewController2, . 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]];
+3

viewControllers - , , , , , , . , , viewController1 , viewController2 , , viewController2.m, :

[[self parentViewController] setString1:string2]

: D

+1

, .

, , , . .

0

Source: https://habr.com/ru/post/1705702/


All Articles