Singleton function not retaining value

95 Views Asked by At

I'll preface this question by saying that I am a total noob when it comes to Objective-C. So please, be patient with my question. :)

So here is my issue. I am basically allowing the user to 'rub out' an image by using alpha blending and such, and then converting the created texture to a CCSprite. I am then able to store the CCSprite in a function within my singleton class. Like so:

erasedTextureSprite = [CCSprite spriteWithTexture:darknessLayer.sprite.texture];

[[MySingleton sharedMySingleton] setRevealTexture:erasedTextureSprite];

Here is the setRevealTexture & getRevealTexture function as well as the revealTexture variable initialisation in my MySingleton.h file:

@interface MySingleton : NSObject
{
    CCSprite *revealTexture;
}

...

-(void) setRevealTexture: (CCSprite *) texture;
-(CCSprite *) getRevealTexture;

And here are both functions in my MySingleton.m file:

-(void) setRevealTexture: (CCSprite *) texture
{
    NSLog(@"set reveal texture.");
    revealTexture = texture;
    NSLog(@"%f", [revealTexture boundingBox].size.width);
}

-(CCSprite *) getRevealTexture
{
    NSLog(@"got reveal texture.");
    NSLog(@"%f", revealTexture.contentSize.width);
    return revealTexture;
}

If I set the reveal texture, and then get it right away, it seems to return the sprite correctly. However, if I set the texture and then transition to another scene, it seems to lose it's value, and throws me an error when I try and call the getRevealTexture function.

Question: Why is my function not retaining it's value when I transition between scenes?

If any more clarification is needed please let me know!

1

There are 1 best solutions below

6
Liviu R On BEST ANSWER

Practically there is no point in using your own setter and getter if your not doing anything fancy. What you are doing is using an iVar which should have been a strong property.

you could achieve the same by doing:

@property (nonatomic, strong) CCSprite *revealTexture;

in your header file. You would then get the following 2 functions by default:

[[MySingleton sharedMySingleton] revealTexture];
[[MySingleton sharedMySingleton] setRevealTexture:texture];

My next point of failure that I would presume if this doesn't work is that your singleton function is not working properly and your actually getting a new instance each time. You can easily find this out by doing in the debugger:

po [MySingleton sharedMySingleton]

And seeing the instance that is returned each time.

example for a basic singleton code:

static MySingleton *__sharedMySingleton = nil;

+ (id)sharedMySingleton {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __sharedMySingleton = [MySingleton new]; // or a specific alloc init function
    });

    return __sharedMySingleton;
}

Due to the request - here is a short image to explain how to enter debugger commands in xcode 5: enter image description here