[Objective-C] basic concepts and usage of reference counting and object ownership in OC

Source: Internet
Author: User

Memory Management Mechanism in cocoa-reference count

Cocoa provides a mechanism to implement the above logical model, known as "reference count" or "Reserved count ". The value of the reference count indicates that several "persons" of the object are using it.

 

  1. Each object has a retain count. when an object is created, the reference count value is 1. When a retain message is sent, the reference count of this object is increased by 1, the reference count of this object is 2. When a release message is sent to this object, the reference count of this object is reduced by 1. When the reference count of an object is 0, the system automatically calls the dealloc method, destroy this object

     

    The following example shows how to increase, decrease, and reference count.

    1: Create the Person class and overwrite the dealloc method:

     

    #import "Person.h"@implementation Person-(void)dealloc{    NSLog(@"person dead");    [super dealloc];}@end

     

    2: Simulate reference counting in the main. m METHOD

     

    #import 
        
         #import "Person.h"int main(int argc, const char * argv[]){    @autoreleasepool {                Person *tom=[[Person alloc]init];        NSLog(@"tom : %ld",[tom retainCount]);        [tom retain];        NSLog(@"tom : %ld",[tom retainCount]);        [tom release];        NSLog(@"tom : %ld",[tom retainCount]);        [tom release];    }    return 0;}
        

     


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.