1

I am trying to use singleton in my app. I want to share 8 strings using a singleton.

This is the tutorial I referred to -> http://www.galloway.me.uk/tutorials/singleton-classes/

My code: - MyManager.h

#import <foundation/Foundation.h>

@interface MyManager : NSObject {
NSString *someProperty1;
NSString *someProperty2;
NSString *someProperty3;
NSString *someProperty4;
NSString *someProperty5;
NSString *someProperty6;
NSString *someProperty7;
NSString *someProperty8;
}

@property (nonatomic, retain) NSString *someProperty1;
@property (nonatomic, retain) NSString *someProperty2;
@property (nonatomic, retain) NSString *someProperty3;
@property (nonatomic, retain) NSString *someProperty4;
@property (nonatomic, retain) NSString *someProperty5;
@property (nonatomic, retain) NSString *someProperty6;
@property (nonatomic, retain) NSString *someProperty7;
@property (nonatomic, retain) NSString *someProperty8;

+ (id)sharedManager;

@end

MyManager.m

#import "MyManager.h"

@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}

- (id)init {
  if (self = [super init]) {
someProperty1 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty2 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty3 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty4 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty5 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty6 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty7 = [[NSString alloc] initWithString:@"Default Property Value"];
someProperty8 = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

- (void)dealloc {
// Should never be called, but just here for clarity really.
}

@end

I want to use this singleton to use these string variables to add string in one other view and then use it to store in database in another third view.

Can someone please tell me how to reference them and store string in these variables and again access them in the third different view?

4

1 回答 1

4
  1. import MyManager.h where you use singleton.
  2. [[MyManager sharedManager] setSomeProperty1:@abc"]; //for setting
  3. [[MyManager sharedManager] someProperty1]; // for getting

or you can use like this also

MyManager *manager = [MyManager sharedManager];
manager.someProperty1 = @"abc";
NSString *str = manager.someProperty1; 
于 2012-07-26T13:42:10.193 回答