0

首先,我来自 Lua,不要怪我是全局变量,哈哈。所以,我一直在阅读有关如何使用整个“单例系统”的信息,但我不确定我是否完全没有抓住重点,或者我只是不正确地实施它?

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

。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)。我是否错误地解释了单身人士的目的?我只是不擅长单身并且没有正确设置吗?有谁知道我怎样才能达到让我的数组计数可以访问我的所有文件的结果?

4

1 回答 1

1

你有几个问题。尝试以下更改:

全局变量.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;
于 2013-03-20T04:53:18.583 回答