Invalid Native Object reported when creating CCSprite in CCLayer::init and accessing it in CCLayer::update

I have a CCLayer with CCSprites in it. When I create and add sprites to the layer in init, everything works fine. If I create sprites in init and access them in update, without adding them to the layer, I get an error: “Cocos2d: JS: Invalid Native Object”. The error is reported for the line accessing the given sprite.

Below is example code giving the error:

var SpriteLayer = cc.Layer.extend({

ctor: function() {
this.*super;
cc.associateWithNative;
this.init;
},
init: function {
this.*super();

cc.SpriteFrameCache.getInstance().addSpriteFrames(“spriteSheet.plist”);
this.*sprite = cc.Sprite.createWithSpriteFrameName;
// When this is uncommented this works
//this.addChild;
this.scheduleUpdate;
},
update: function {
this.*sprite.setPosition(cc.p(120,120));
}
});

I am using XCode and the problem appears in simulators and on device. I am using Cocos2d-x v2.1rc0-x-2.1.2 with the hotfix. This works with the HTML5 version.

If you only want to save node after it’s created, you should invoke this._sprite.retain; and when you don’t need it, please call this._sprite.release;.
This is because we are using the lifecycle of cpp to control the lifecycle of js.
When a cocos2d object is created, it’ll be an autorelease object. If you don’t add it to any nodes, it will be released at the end of current mainloop.

Thank you for your reply!

I thought it sounds like an autorelease issue, but I didn’t realize it actually is a feature. I am still new to Cocos2D-X, and haven’t seen this in the documentation. Looking forward to seeing C2DX evolve, it’s an awesome platform!