0

I am new to objective-C and working on an app in which there are multiple viewController Files. I need to access Value of variables set in one file to be accessible in other files. How can i implement this.

What i was doing that i created a class Globals.m and declared variables in it.

#import <Foundation/Foundation.h>

@interface Globals : NSObject

@property  NSString*  firstName;
@property NSString* lastName;
@property NSString* emailId;

@end

My question are: 1.will the above Declaration make these variables retain there values in different files?

  1. Where should i crete a object of this class which should be accessible in all files.
martin jakubik
  • 4,168
  • 5
  • 29
  • 42
Junior Bill gates
  • 1,858
  • 4
  • 20
  • 33

1 Answers1

2

I'd maybe suggest using a Singleton pattern as it will allow you to hold an instance of the class through your app. So you could set firstName in one class and get it in another.

MySingleton.h

@interface MySingleton : NSObject

// Our properties we want to set.
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *emailName;
// etc...

// Our class method for getting the shared instance.
+ (MySingleton *)sharedInstance;

@end

MySingleton.m

#import "MySingleton.h"

@implementation MySingleton

+ (MySingleton *)sharedInstance
{
    static dispatch_once_t pred = 0;
    static id sharedObject = nil;
    dispatch_once(&pred, ^{
        sharedObject = [[self alloc] init];
    });

    return sharedObject;
}

@end

Then in your other classes all you need to do is import the MySingleton class and do something like :

MySingleton *singleton = [MySingleton sharedInstance];
[singleton setFirstName:@"Bob"];

For more information on Singleton Patterns and other Design Patterns here is a tutorial that you could read through iOS Design Patterns. Also a good read is Correct Singleton Pattern Objective C (iOS)?

Community
  • 1
  • 1
Popeye
  • 11,839
  • 9
  • 58
  • 91