Pass a variable between lots of UIVIewControllers

后端 未结 6 578
迷失自我
迷失自我 2021-01-02 15:37

In my iPhone app, there is a setup assistant which helps users to input a lot of data. It\'s basically a UINavigationController with lots of UIViewControllers in it. Now, at

6条回答
  •  走了就别回头了
    2021-01-02 16:22

    A simple yet reusable and extensible way to solve this problem is using a singleton.

    Declare a new class named SetupConfig, for example.

    Your SetupConfig.h should then look as follows:

    @interface SetupConfig : NSObject {
        NSString *_myString;
    }
    
    @property (retain) NSString *myString;
    
    + (id)sharedSetupConfig;
    
    @end
    

    And the corresponding SetupConfig.m:

    #import "SetupConfig.h"
    
    SetupConfig *g_sharedSetupConfig = nil;
    
    @implementation SetupConfig
    
    @synthesize myString = _myString;
    
    + (id)sharedSetupConfig {
        if (!g_sharedSetupConfig) {
            g_sharedSetupConfig = [[SetupConfig alloc] init];
        }
    }
    
    @end
    

    Now, in the view controller implementation you want to access myString from:

    @import "MyViewController.h"
    @import "SetupConfig.h"
    
    @implementation MyViewController
    
    - (void)methodDoingSomethingWithSingletonString
    {
        NSString *myString = [[SetupConfig sharedSetupConfig] myString];
    } 
    
    @end
    

    The singleton approach comes with a number of advantages over using a global C variable. First of all you do not have to re-declare your global variables over and over. What is more, your "global" variables are encapsulated in a class. Synthesizing property getters/setters is a nice way to abstract the actual variable away from the rest of your code. Finally, this implementation may be integrated into unit tests easily.

提交回复
热议问题