Analysis of cocos2d-x memory management related operations in IOS development _ios

Source: Internet
Author: User
Tags addchild

One, iOS with picture memory
On iOS, the picture is automatically scaled to the N-second size of 2. For example, a picture of 1024*1025, the memory occupied with a picture of 1024*2048 is consistent. The formula for calculating the memory size of a picture is a long * wide *4. The memory occupied by such a 512*512 is 512*512*4 = 1M. Other sizes and so on. (The maximum size supported on Ps:ios is 2048*2048).

Second, Cocos2d-x's picture caching
Cocos2d-x uses Spritewithfile or spritewithspriteframename when constructing an elf, and cocos2d-x loads the picture into the cache either way. If this is the first time the picture is loaded, the picture is loaded into the cache and then read from the cache. If the cache already exists, it is extracted directly from the cache and is exempt from the loading process.

The caching of pictures is mainly handled by the following two classes: Ccspriteframecache, Cctexturecache

Ccspriteframecache is loaded with a large, tiled image, each of which is just one area of the larger image, which is saved in the plist file. It can be loaded into the area just by the name of the small map.

Cctexturecache is a normal picture cache, all of our directly loaded pictures will be placed by default in this cache, to improve the efficiency of the invocation.

Therefore, the entire picture is loaded into memory each time a picture is loaded, or a mosaic is loaded by plist. If it is not released, it will be occupied all the time.

Third, rendering memory
Do not assume that when calculating memory, only the memory loaded into the cache can be computed. Take a picture of 1024*1024 as an example.

Copy Code code as follows:

Ccsprite *psprite = Ccsprite::spritewithfile ("A.png");

After calling this line of code, you can see it in the leaks tool, adding approximately 4M of memory. and then call
Copy Code code as follows:

AddChild (Psprite);

At this point, the memory has increased by 4M. That is, a picture, if it needs to be rendered, the memory it occupies will be X2.

Then look at the pictures loaded through the plist, such as the large size of the 2048*2048. Want to load a small picture of one of the 32*32

Copy Code code as follows:

Ccspriteframecache::sharedspriteframecache ()->addspriteframeswithfile ("B.plist");

At this time the memory increased by 16M (Khan)
Copy Code code as follows:

Ccsprite *pspriteframe = Ccsprite::spritewithspriteframename ("B1.png");

B.png size is 32*32, think is to add a little bit of memory, but the actual situation is to increase 16M of memory. That is, as long as a portion of it is rendered, the entire picture is loaded together.

But the situation is not so bad, these already rendered pictures, if loaded again, the memory will not continue to rise, such as the addition of 100 b.plist another area, picture memory or a total increase 16+16 = 32M, and will not continue to rise.

Four, Cache release
If the game has a lot of scenes, when switching scenes can be the first scene of the memory release, to prevent the total memory too high.

Copy Code code as follows:

Cctexturecache::sharedtexturecache ()->removealltextures (); Release all loaded pictures so far

Cctexturecache::sharedtexturecache ()->removeunusedtextures (); Release the Cctexturecache::sharedtexturecache ()->removetexture () by a picture with a reference count of 1; Free a picture alone

Ccspriteframecache is similar to the Cctexturecache release method.


It is worth noting that the timing of the release, generally in the switch to release resources when the scene, if from A scene switch to B scene, call the function order for b::init ()---->a::exit ()---->b::onenter () If you use the switching effect, such as ctransitionjumpzoom::transitionwithduration functions, the call order of the function changes to B::init ()---->b::onenter ()---->a::exit () And the second way there will be a moment to stack two of scenes of resources, if not to overdo it, it is likely to crash because of memory crunch.

Sometimes when all resources are forced to be freed, an executing animation is thrown out of reference and an exception is ejected, and Ccactionmanager::sharedmanager ()->removeallactions () can be invoked to resolve.

Five, memory management
1. Overview
Cocos2d-x was originally transplanted from Cocos2d's objective C version. Therefore, in memory management, a reference counter method similar to NSObject is used, and the related interface is placed in the Ccobject class.

2. Reference counter--Manually manage memory
The reference count is automatically set to 1 when the object of the Ccobject and its subclasses is created. After each call to retain, the reference count is +1. Reference count-1 per call release, and if reference count = 0, direct delete this.
The relevant interfaces are as follows:

Copy Code code as follows:

Number of references +1
virtual void ccobject::retain (void);
Number of references-1; if the reference counter = 0, delete this;
virtual void ccobject::release (void);
Helper method to quickly determine that the current object has only a unique reference
BOOL Ccobject::issinglerefrence (void);
Returns the number of references
unsigned int ccobject::retaincount (void);

Principle 1: Who generates (new, copy) who is responsible for release.
Example:
Copy Code code as follows:

Ccobject *obj=new Ccobject;
...
Obj->release ();

Retain is used when pointers are passed and assigned, meaning that they are owned. This is often used on pointer assignment.
Principle 2: Who retain, who is responsible for release.
Example:

Copy Code code as follows:

Obj->retain ();
...
Obj->release ();

Principle 3: When passing assignment, you need to first retain the formal parameters, then release the original pointer, and finally assign the value. (Note that since you are not using a self assignment check here, the order cannot be wrong.) )
Example:

Copy Code code as follows:

void Ccnode::setgrid (ccgridbase* pgrid)
{
Cc_safe_retain (Pgrid);
Cc_safe_release (M_pgrid);
M_pgrid = Pgrid;
}


3. Automatic release pool-Manage memory automatically

Principle 4: For objects that use autorelease, you do not have to worry about it, which is automatically released after each frame ends.

Related interfaces:

Copy Code code as follows:

ccobject* ccobject::autorelease (void);

Example:
Copy Code code as follows:

Ccobject *obj=new Ccojbect;
Obj->autorelease ();
...

Completely manual memory management, very cumbersome, Cocos2d-x provides an automatic release pool Ccpoolmanager. The objects in the pool are automatically released when the object is placed in an automatic release pool, and each frame draws to the end.


4.CCNode Node Management

Cocos2d-x uses nodes to make up a tree, which is used to traverse the tree when rendered. Ccnode is the parent of all node classes, where he uses a Ccarray object to manage all of his child nodes, and when the object is added as a child node, it is actually added to the Ccarray object, and the Retain method of the object is invoked. Similarly, the release method is invoked when removing from the Ccarray.

Related interfaces:

Copy Code code as follows:

virtual void AddChild (Ccnode * child);
virtual void AddChild (Ccnode * child, int zOrder);
virtual void AddChild (Ccnode * child, int zOrder, int tag);
virtual void RemoveChild (ccnode* child, bool cleanup);
void Removechildbytag (int tag, bool cleanup);
virtual void Removeallchildrenwithcleanup (bool cleanup);

When switching scenes, the system traverses the entire tree node for release.

5. Static Factory

There are a number of static factory methods in Cocos2d-x, all of which call the Autorelease function on the this pointer. As in Ccsprite, these methods are:

Copy Code code as follows:

Static ccsprite* spritewithtexture (Cctexture2d *ptexture);
Static ccsprite* spritewithtexture (cctexture2d *ptexture, const ccrect& rect);
Static ccsprite* spritewithtexture (cctexture2d *ptexture, const ccrect& rect, const ccpoint& offset);
Static ccsprite* Spritewithspriteframe (Ccspriteframe *pspriteframe);
Static ccsprite* spritewithspriteframename (const char *pszspriteframename);
Static ccsprite* spritewithfile (const char *pszfilename);
Static ccsprite* spritewithfile (const char *pszfilename, const ccrect& rect);
Static ccsprite* Spritewithbatchnode (Ccspritebatchnode *batchnode, const ccrect& rect);

These methods are implemented internally: memory allocation, initialization, and setting of Autorelease. Using static factories to generate objects simplifies the code and is the official recommended method.

6.cache Mechanism class

There are some cache classes in the Cocos2d-x, which are the managers of a single instance class.

Copy Code code as follows:

Ccanimationcache
Ccspriteframecache
Cctexturecache

These cache internals also use the Ratain and release methods to prevent these resources from being released.
With these cache, we can save some of the preloaded resources, call it at your convenience, and bind it to some objects. Note that these cache is not automatically deleted when the scene is switched, and you need to manually invoke the Purgexxxx method to clean it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.