Using global variables in Objective-C

后端 未结 6 871
一个人的身影
一个人的身影 2020-12-07 19:33

First of all, I tried almost all the solutions given in stackoverflow but I didn\'t succeed in implement global vars, I even did a step by step tutorial and still I get the

6条回答
  •  余生分开走
    2020-12-07 20:06

    One way to implement global variables, and to manage their lifetime (i.e. that they are initialized) and even to provide global methods is to implement a class exposing those variables/methods and to use the singleton pattern:

    GlobalVars.h:

    #import 
    
    @interface GlobalVars : NSObject
    {
        NSMutableArray *_truckBoxes;
        NSMutableArray *_farmerlist;
        NSString *_farmerCardNumber;
        NSString *_fName;
    }
    
    + (GlobalVars *)sharedInstance;
    
    @property(strong, nonatomic, readwrite) NSMutableArray *truckBoxes;
    @property(strong, nonatomic, readwrite) NSMutableArray *farmerList;
    @property(strong, nonatomic, readwrite) NSString *farmerCardNumber;
    @property(strong, nonatomic, readwrite) NSString *fName;
    
    @end
    

    GlobalVars.m:

    #import "GlobalVars.h"
    
    @implementation GlobalVars
    
    @synthesize truckBoxes = _truckBoxes;
    @synthesize farmerList = _farmerList;
    @synthesize frameCardNumber = _frameCardNumber;
    @synthesize fName = _fName;
    
    + (GlobalVars *)sharedInstance {
        static dispatch_once_t onceToken;
        static GlobalVars *instance = nil;
        dispatch_once(&onceToken, ^{
            instance = [[GlobalVars alloc] init];
        });
        return instance;
    }
    
    - (id)init {
        self = [super init];
        if (self) {
            _truckBoxes = [[NSMutableArray alloc] init];
            _farmerlist = [[NSMutableArray alloc] init];
            // Note these aren't allocated as [[NSString alloc] init] doesn't provide a useful object
            _farmerCardNumber = nil;
            _fName = nil;
        }
        return self;
    }
    
    @end
    

    You can then use these global variables like this, for example:

    GlobalVars *globals = [GlobalVars sharedInstance];
    globals.fName = @"HelloWorld.txt";
    [globals.farmerList addObject:@"Old Macdonald"];
    [self processList:[globals farmerList]];
    

    However, please consider:

    • You don't need to use global variables like this; you should be able to create a model object which is created as necessary and reference to it passed to the views. This is MVC.
    • You also posted a stack trace of an unrelated issue which is extremely common with Objective-C; only you can fix this error, once you realize what it is.

提交回复
热议问题