Domanda

I would like to access few values globally in my iOS App. Apart from using the NSUserDefaults, or initialising in a Class and then creating object wherever I want it, is there another simpler way.

I tried using extern keyword, but arm64 do not support it.

Thanks a lot in advance.

È stato utile?

Soluzione 2

I suggest to use singleton, but if it is not suitable for you you can use extern. It is supported and should be used following way:

Default.h

extern NSString *const DGDidLogInNotification;
extern NSArray *array;

Default.m

#import "Default.h"
NSString *const DGDidLogInNotification = @"DGDidLogInNotification";
NSArray *array;

So if you need your variable somewhere - just paste #import "Default.h"

Altri suggerimenti

If you have severeal ViewController and you want to access some globale variables I would recommend a Singleton Data-Class like this:

/**
 * GlobalData.h
 */ 

@interface GlobalData : NSObject {    

  NSString *foobar;     

}    

@property(nonatomic,strong)NSString *foobar;    

+(GlobalData*)getInstance;    

@end  


/**
 * GlobalData.m    
 */

@implementation GlobalData
@synthesize foobar;

static GlobalData *instance = nil;    

+(GlobalData *)getInstance {
    @synchronized(self) {    
        if( instance == nil ) {    
            instance = [GlobalData new];    
        }    
    }    
    return instance;    
}  

You can now access the same variables from everywhere like this:

#import GlobalData.h

GlobalData *globalData = [GlobalData getInstance];  
globalData.foobar = @"foobar";  

Based on your requirements, I'd recommend creating properties in your AppDelegate's header file:

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, assign) BOOL someGlobalVariable;

@end

Then, to access (in this case assign) the variable in your view controller,

#import "AppDelegate.h"
#import "ViewController.h"

((AppDelegate *)[[UIApplication sharedApplication] delegate]).someGlobalVariable = YES;

There's a file named {project_name}-Prefix.pch in your project. You can declare any object or variable in this file and it will be accessible in any other place of the project. For example:

#ifndef __IPHONE_4_0
#warning "This project uses features only available in iOS SDK 4.0 and later."
#endif


#ifdef __OBJC__
  #import <UIKit/UIKit.h>
  #import <Foundation/Foundation.h>
#endif


NSInteger someVariable = 10;

Now you can access to someVariable anywhere. Also you can import to Prefix.pch any file where you have variable declared and all public variables and objects will be accessible in all other files.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top