Jacob Sharf
Jacob Sharf

Reputation: 250

Objective C instance variable is released despite being retained

I have a marshmallow class which has (among other things) a CCSprite object as an instance variable.

here is the init method:

-(id) init
{
    if((self = [super init]))
    {   
        model = [[CCSprite spriteWithFile:@"marshmallow.png"] retain];
        maxSpeed = 5; //160px per second (maxspeed * PTM_Ratio = px/second max)
        gravity = 9.81; // in meters/sec^2
        health = 3;
    }

    return self;
}

the variable is declared in another file as a global variable with the line:

Marshmallow *mainChar;

Later in the file, it is set (initiated/alloc'd) with this line:

mainChar = [[mainChar alloc] init];

while writing the previous line, xcode gave me a warning that Marshmallow might not respond to alloc. (I don't think that's related. just mentioning anything that seems wrong)

my problem is that the following line of code returns nil:

[mainChar getModel];

why does it return nil instead of the instance variable?

here is the getModel function:

-(CCSprite *)getModel
{
    return model;
}

Upvotes: 0

Views: 489

Answers (3)

Nate Thorn
Nate Thorn

Reputation: 2183

Your problem is in the initialization of your mainChar variable. The line you're looking for is this:

mainChar = [[mainChar alloc] init];

The warning you got is telling you that instances of type Marshmallow will not respond to the -alloc message. That is your problem: you want to call the +alloc class method instead, like so:

mainChar = [[Marshmallow alloc] init];

Upvotes: 2

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

I think you want to do

mainChar = [[MarshMallow alloc] init];

instead of

mainChar = [[mainChar alloc] init];

The error message you got is very important.

Upvotes: 1

sidyll
sidyll

Reputation: 59297

mainChar = [[mainChar alloc] init];

Shouldn't be

mainChar = [[Marshmallow alloc] init];

?

The message says an object from that class might not respond to it, not the class itself.

Upvotes: 4

Related Questions