如何引用单身人士?

时间:2012-07-26 13:36:31

标签: objective-c singleton

我正在尝试在我的应用中使用单例。我想用单身人士分享8个字符串。

这是我提到的教程 - > http://www.galloway.me.uk/tutorials/singleton-classes/

我的代码: - 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

我想使用这个单例来使用这些字符串变量在另一个视图中添加字符串,然后使用它在另一个第三个视图中存储在数据库中。

有人可以告诉我如何引用它们并在这些变量中存储字符串并再次在第三个不同的视图中访问它们吗?

1 个答案:

答案 0 :(得分:4)

  1. 导入MyManager.h,使用单例。
  2. [[MyManager sharedManager] setSomeProperty1:@abc"]; //for setting
  3. [[MyManager sharedManager] someProperty1]; // for getting
  4. 或者您也可以这样使用

    MyManager *manager = [MyManager sharedManager];
    manager.someProperty1 = @"abc";
    NSString *str = manager.someProperty1;