在单例中访问可变值?

时间:2013-03-20 04:44:36

标签: iphone ios objective-c variables singleton

首先,我来自Lua,不要责怪我是全球变量lol。所以,我一直在阅读如何使用整个“Singleton系统”,我不确定我是否完全忽略了这一点,或者我是否只是错误地实现它?

我的代码的目标是为多个文件创建一种方法来访问一个包含特定文件中数组大小的变量。这是我的单身人士:

·H

#import <Foundation/Foundation.h>

@interface GlobalVariables : NSObject
{
    NSNumber *currentGameArrayCount;
    BOOL *isGamePaused;
}

@property (nonatomic, readwrite) NSNumber *currentGameArrayCount;
@property (nonatomic, readwrite) BOOL *isGamePaused;

+ (GlobalVariables *)sharedInstance;


@end

的.m

#import "GlobalVariables.h"

@implementation GlobalVariables
@synthesize currentGameArrayCount, isGamePaused;

static GlobalVariables *gVariable;

+ (GlobalVariables *)sharedInstance
{


    if (gVariable == nil) {
        gVariable = [[super allocWithZone:NULL] init];
    }

    return gVariable;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        currentGameArrayCount = [[NSNumber alloc] initWithInt:0];
        isGamePaused = NO;

    }

    return self;
}

@end

并在我使用的数组的另一个文件中:

GlobalVariables *sharedData = [GlobalVariables sharedInstance];
        NSNumber *tmpArrayCount = [sharedData currentGameArrayCount];

        NSInteger tmpCount = [whereStuffActuallyHappens.subviews count]; // Subviews is the array
        NSNumber *currentCount = [NSNumber numberWithInteger:tmpCount];


        tmpArrayCount = currentCount;

这段代码的希望是在singeton(currentGameArrayCount)中获取变量并将其设置为当前数组计数(currentCount)。我错误地解释了单身人士的目的吗?我是不是很擅长单身而且没有正确设置?有谁知道如何实现让我的数组计数可以访问我的所有文件的结果?

1 个答案:

答案 0 :(得分:1)

你有一些问题。尝试这些更改:

GlobalVariables.h:

#import <Foundation/Foundation.h>

@interface GlobalVariables : NSObject

@property (nonatomic, assign) int currentGameArrayCount;
@property (nonatomic, assign) BOOL gamePaused;

+ (GlobalVariables *)sharedInstance;

@end

GlobalVariables.m:

#import "GlobalVariables.h"

static GlobalVariables *gVariable = nil;

@implementation GlobalVariables

+ (GlobalVariables *)sharedInstance {
    if (gVariable == nil) {
        gVariable = [[self alloc] init];
    }

    return gVariable;
}

- (id)init {
    self = [super init];
    if (self) {
        self.currentGameArrayCount = 0;
        self.gamePaused = NO;
    }

    return self;
}

@end

现在,您可以使用其他代码:

GlobalVariables *sharedData = [GlobalVariables sharedInstance];
int tmpArrayCount = sharedData.currentGameArrayCount;

NSInteger tmpCount = [whereStuffActuallyHappens.subviews count]; // Subviews is the array
sharedData.currentGameArrayCount = tmpCount;