Я впервые использую синглтон и не знаю, как его реализовать ...
Хорошо, мне нужно объяснить некоторые вещи:
В Hexagon.h (который наследуется от CCNode) я хочу создать несколько спрайтов (здесь называемых «шестиугольниками»). Однако они еще не добавлены на сцену. Они добавляются в класс HelloWorldLayer.m , вызывая Hexagon *nHex = [[Hexagon alloc]init];
. Это верно ? Затем он повторяет цикл for и создает все шестиугольники или только один?
В любом случае, у меня есть одноэлементный класс, который должен обрабатывать всю информацию о состоянии общедоступной игры, но поиск пока невозможен. Например, я не могу получить значение existingHexagons
, потому что оно возвращает (null)
объектов. Либо я неправильно установил объекты, либо я ложно извлекаю данные из синглтона. На самом деле, я даже был бы признателен за ответ на один из этих вопросов. Пожалуйста, помогите мне. Если что-то не понятно, пожалуйста, добавьте комментарий, и я постараюсь уточнить это.
Сейчас у меня есть следующее:
GameStateSingleton.h
#import <Foundation/Foundation.h>
@interface GameStateSingleton : NSObject{
NSMutableDictionary *existingHexagons;
}
+(GameStateSingleton*)sharedMySingleton;
-(NSMutableDictionary*)getExistingHexagons;
@property (nonatomic,retain) NSMutableDictionary *existingHexagons;
@end
GameStateSingleton.m
#import "GameStateSingleton.h"
@implementation GameStateSingleton
@synthesize existingHexagons;
static GameStateSingleton* _sharedMySingleton = nil;
+(GameStateSingleton*)sharedMySingleton
{
@synchronized([GameStateSingleton class])
{
if (!_sharedMySingleton)
[[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
+(id)alloc
{
@synchronized([GameStateSingleton class])
{
NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
}
return self;
}
@end
Hexagon.m
-(CCSprite *)init{
if( (self=[super init])) {
NSString *mainPath = [[NSBundle mainBundle] bundlePath];
NSString *levelConfigPlistLocation = [mainPath stringByAppendingPathComponent:@"levelconfig.plist"];
NSDictionary *levelConfig = [[NSDictionary alloc] initWithContentsOfFile:levelConfigPlistLocation];
NSString *currentLevelAsString = [NSString stringWithFormat:@"level%d", 1];
NSArray *hexPositions;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
hexPositions = [[levelConfig valueForKey:currentLevelAsString] valueForKey:@"hexpositionIpad"];
}
else{
hexPositions = [[levelConfig valueForKey:currentLevelAsString] valueForKey:@"hexpositionIphone"];
}
NSString *whichType = [NSString stringWithFormat:@"glass"];
CGSize screenSize = [CCDirector sharedDirector].winSize;
if ([whichType isEqualToString:@"stone"]){
hexagon = [CCSprite spriteWithFile:@"octagonstone.png"];
}else if([whichType isEqualToString: @"glass"]){
hexagon = [CCSprite spriteWithFile:@"octagoncolored1.png"];
}else if([whichType isEqualToString: @"metal"]){
hexagon = [CCSprite spriteWithFile:@"octagonmetal.png"];
}
NSMutableDictionary *eHexagons =[[GameStateSingleton sharedMySingleton] getExistingHexagons];
for (int i=0;i < [hexPositions count];i++){
CGPoint location = CGPointFromString([hexPositions objectAtIndex:i]);
CGPoint nLocation= ccp(screenSize.width/2 + 68 * location.x,screenSize.height/2 + 39 * location.y);
NSString *aKey = [NSString stringWithFormat:@"hexagon%d",i];
hexagon =[CCSprite spriteWithFile:@"octagoncolored1.png"];
hexagon.position = nLocation;
[eHexagons setObject:hexagon forKey:aKey];
[self addChild:[eHexagons valueForKey:aKey] z:3];
[[GameStateSingleton sharedMySingleton]setExistingHexagons:eHexagons];
}
NSLog(@"these are the existinghexagons %@", existingHexagons);
//This returns a dictionary with one (null) object
}
return hexagon;
}
HelloWorldLayer.m -> -(id)init
method
Hexagon *nHex = [[Hexagon alloc]init];