Memory Allocation and release in IOS

Source: Internet
Author: User

In IOS programming, memory operations are inseparable. When I first came into contact with IOS programming, this is always caused by such memory problems.ProgramCrash.

In fact, the release of memory in IOS programming is relatively simple. You only need to release or autorelease your own retain, new, alloc, copy, and mutablecopy objects. One principle is: If you allocate storage, you are responsible for release.

In addition, you should note that many methods will automatically retain the added objects, such:

Nsstring * test = [[nsstring alloc] initwithformat: @ "% d", 111];
Nslog (@ "% d", [test retaincount]); // The retain of test is 1 at this time
Nsmutablearray * array = [[nsmutablearray alloc] initwithobjects: Test, nil];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 2. Because the test object is added to the array, test is retain.
[Array addobject: Test];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 3. Because the test object is added to the array, the test will be retain.
[Array release];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 1, and the array is released. It Automatically releases its internal objects, so the retain count of test is changed back to 1.

So after calling a method like addobject: test, if you are not using the test object, release it without worrying about "if I release test, so will the test in array be lost?" If you don't release it, it will lead to memory leakage.

Retaincount is similar to the reference count in Java. When retaincount is 0, the dealloc method of the object is called to release the object.

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.