How to Access Objects from one ViewController to another ViewController

前端 未结 3 978
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-11 00:50

Provide some tips to get rid of the following scenario.

Description:

I have two viewControllers namely ViewController1 and ViewController2, so

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-11 01:24

    That depends on where the code you want to set string1 in is being run. If it is in some outside class with access to both view controller objects, then it's simple. If you have ViewController1 object vc1, and ViewController2 object vc2, then all you do is:

    [vc1 setString1:[vc2 string2]];
    

    If you want to set string1 from code run within ViewController2, then you use the notification mechanism. In ViewController1's initialization routine, you put:

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

    And define:

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

    Then, in ViewController2, when you want to change the string:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:self];
    

    The same technique is used when you are changing the string from some third class that has access to vc2 but not vc1. ViewController1 code is the same as above, and when you want to change the string:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:vc2];
    

    The trickiest part is if you want to change the string from within ViewController1 (assuming that you don't have access to the object vc2). You have to use two notifications: the one above, and also, for ViewController2:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(launchTheOtherNotificationMethod:) name:@"anotherNotificationName" object:nil];
    
    -(void)launchTheOtherNotificationMethod:(NSNotification)notification{
         [[NSNotificationCenter defaultCenter] postNotificationName:@"anyStringJustMakeItUnique" withObject:self];
    }
    

    Then, when you want to change the string:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"anotherNotificationName" withObject:nil];
    

    If you think this is too complex or causes too much overhead, the simpler solution is to have, as fields in ViewController1 and ViewController2, pointers to one another. Then, within ViewController1:

    string1 = [myVC2 string2];
    

    And if you make these fields properties, then, from the outside:

    [vc1 setString1:[[vc1 myVC2] string2]];
    

    And even:

    [[vc2 myVC1] setString1:[vc2 string2]];
    

提交回复
热议问题