IOS understands reference counting

Source: Internet
Author: User

A Brief introduction

OC language uses reference counting to manage memory each object has a counter that can increment or decrement, and if you want an object to continue to survive, increment its reference count, use it, decrement its count, and the count becomes 0, destroy it.



two How reference counting works

The NSObject protocol declares the following three methods for manipulating counters to increment or decrement their values

Retain incrementing reference count

Release Decrement reference count

Autorelease the reference count is decremented when the "auto-free pool" is cleaned up later


To avoid inadvertently using invalid objects, the pointer will be emptied after the release is generally called. This ensures that pointers that may point to high invalid objects are not present, which is commonly referred to as dangling pointer.



three return cycle

One of the most frequently asked questions when using the reference counting mechanism is the return cycle, which is to refer to multiple objects in a circular form, which leads to memory leaks because objects in the loop will not have their retention count reduced to 0. For each object in the loop, there is at least one other object that references it, and the garbage collector recycles all the objects that are referenced to each other, while OC references the technical architecture, which is less convenient, often using weak reference to solve the sub-problem, thus avoiding memory leaks


IOS understands reference counting

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.