[Study note-objective-c] "objective-c-Basic Tutorial 2nd Edition" chapter Nineth memory Management

Source: Internet
Author: User

Memory Management:

    • Ensure that memory is allocated when needed, freeing up memory at the end of program run
    • If you allocate only memory without freeing up memory, a memory leak occurs (leak memory), and the program's footprint is increasing, eventually draining and causing the program to crash.
    • Do not use any newly freed memory, or you may misuse stale data, and if the memory has already loaded other data, it will break the new data.
9.1 Object Life Cycle

The life cycle of an object:

    1. Birth: Implemented by Alloc or new method
    2. Survive: Accept messages and perform actions
    3. Dating: Passing functions through compositing and to methods
    4. To die: To be released
9.11 Reference count

About the reference count operation:

    • Increase the value of the retention counter for the object: send retain. Method:-(id) retain //返回值为id类型
[[Car retain] setTire: tire atIndex: 2]; //car object keeps the value of the counter +1 and performs the operation of setTire
    • Reduce the value of the object's retention counter: send release. Method:(oneway void)release;
    • Gets the current value of the hold counter: Retaincount. Method:-(NSUInteger) retainCount;//格式化方法:%ld
    • The DEALLOC message is automatically sent to the object when the reserved counter of the object is returned to 0 o'clock.
    • You can override the Dealloc method in your own object, which frees all related resources that have already been allocated, and you cannot call the Dealloc method directly.
9.12 Object Ownership
    • When an entity owns an object, the entity is responsible for cleaning up the objects it owns
      • If an object has an instance variable that points to another object, the object is said to have these objects
      • If a function creates an object, it is said that the function owns the object
Newnew]; / / engine has engine object [car setEngine: engine]; / / car has engine object}

Note : both main () and car classes have engine objects, how can I release them?

    • Let the car class keep the engine object in the Setengie method, main () releases the engine object, and the car class releases the engine object when the task is completed.
9.13 Retention and deallocation in Access methods
-(void)setEngine: (Engine *)newEngine
     [newEngine retain]; //Preserve new objects first
     [engine release]; / / release the old object
     Engine = newEngine;
9.14 Automatic Release
-(NSString *) description
    NSString *description = [[NSString alloc] initWithFormat:@"I am %d years old", 4];
    return (destription);

    NSString *desc = [someObject description];
    [desc release];

Note : How is the string object created in the description method freed?

9.15 all objects into the pool
-(id)autorelease;//return the object that accepts this message
    • When a autorelease message is sent to an object, the object is added to the auto-free pool, and the release message is sent like all objects in the pool when the auto-free pool is destroyed.
-(NSString *) description
     NSString *description = [[NSString alloc] initWithFormat:@"I am %d years old", 4];
     Return ([destription autorelease]); / / object temporarily put into the pool, after the end of the call NSLog code, the automatic release pool will be automatically destroyed

     NSLog(@"@",[someObject description]);
9.16 Automatic release pool destruction time slightly 9.17 workflow for automatically releasing a pool
Int main ()
     NSAutoreleasePool *pool;
     Pool = [[NSAutoreleasePool alloc] init];

     RetainTracker *tracker;
     Tracker = [RetainTracker new]; // count: 1

     [tracker retain]; // count: 2
     [tracker autorelease]; // count: still 2, the autorelease pool has a reference to the object. When the autorelease pool is destroyed, a release message will be sent to the tracker object. The value of the reserved counter is still greater than 0 and is still active.

     [tracker release]; // count: 1

     NSLog (@"releasing pool");
     [pool release]; //dealloc method call

     Return (0);
9.2 Cocoa's memory management rules
    • When you create an object using New,alloc, or the Copy method, the object's retention counter is 1.
    • If you get an object from another object, assuming that the object has a retention counter value of 1, and that a scene is set to be automatically freed, you do not need to take any action to ensure that the object is cleaned up.
    • If you intend to have an object for some time, you need to keep it and make sure that it is released when the operation is complete.
    • If you keep an object, you need to eventually release or automatically dispose of the object. The Retain method must be kept equal to the number of times the release method is used.

Note : When you have an object, you need to figure out: How do I get the object? How long do you intend to have?

9.21 Temporary objects

If you do not intend to have objects for a long time: temporary objects

    • If this object is obtained using the New,alloc,copy method, the memory release of the object needs to be arranged.
    • A method other than new,alloc,copy obtains an object, you can assume that the value of the reserved counter is 1 and is set to auto-release when the object is returned.
9.22 Owning objects

Always have an object in a multi-segment code and add them to a collection such as Nsarray or nsdictionary

    • If you use the New,alloc,copy method to obtain an object, you only need to release it in the Dealloc method that owns the object.
-(void)dostuff{ new//count:1}
-(void) dealloc{ [flonkArray release]//count:0 [super dealloc];}
    • If an object is obtained using a method other than New,alloc,copy, the object needs to be persisted because the object receives a release message after the event loop ends or when the auto-free pool is destroyed.
-(void)dostuff{    flonkArray = [NSMutableArray arrayWithCapacity:17//count:1,autoreleased}
-(void) dealloc{ [flonkArray release]//count:0  [super dealloc];}

Note: The time for the auto-free pool to be cleaned is completely deterministic: you manually destroy it yourself in the code, and end at the end of the event loop when you use AppKit.

9.23 garbage Collection: automatic memory management mechanism

The garbage collector periodically checks variables and objects and tracks their pointers, and finds that no variable points to an object, and treats the object as garbage that should be discarded.

If the instance variable points to an object, be sure to assign the instance a value of nil, cancel the reference to the object, and tell the garbage collector that the object can be cleaned up.


    • Garbage collection only supports OSX development and cannot be used on iOS apps. Apple does not recommend using the Autorelease method in its own code, nor does it use a handy way to return objects that are automatically freed:stringWith:
    • The garbage collector works at run time, checking the object periodically with the returned code
9.24 Automatic Reference counting
    • Auto reference count (automatic refrence Counting,arc): The system tracks the object and decides which one will still be used and which one will not be used again.

    • Arc works at compile time, and the retain and release statements are inserted in the code.

    • Valid range: The object pointer that can be persisted

      • Code block pointers
      • Objective-c pointer
      • pointer defined by attribute((nsobject)) type
    • Conditions that are satisfied with arc:

      • Ability to determine which objects require memory management
      • Ability to surface how to manage objects
      • There is a viable way to pass ownership of an object
    • A reference to the B,b reference counter +1, strong pointer; referenced +1

    • A released the reference counter of the B,b-1; Released-1

    • Zero Weak reference: zeroing weak reference If the referenced object is disposed, if the reference is set to 0

Declaring a zero weak reference:

    • _weak NSString *mystring
    • @property (weak) NSString *myString

Note: Memory management keywords and features cannot be used together

If the garbage collection mechanism is disabled, you can use the arc
Ensure code conforms to ARC requirements before conversion
Once converted to an arc version, it is no longer possible to restore

    • Owner permissions: To make arc easier to work with, you need to tell the compiler which object is the owner of the pointer.

      • (_bridge) passes a pointer but does not pass its ownership
      Cfstring = (_bridge CFStringRef)theString;
      //The ownership of the pointer is still reserved by theString 
      • (_bridge_retain): Transfer of ownership to Non-rop

        Cfstring = (_bridge_retain CFStringRef)theString;
        //cfstring has a pointer and keeps the counter +1 
      • (_bridge_transfer): Ownership given to ROP

        ARC owns the object and ensures that it will be released just like any other ARC object
9.3 Exceptions

NSException class to represent exceptions

    • Throws an exception (raises an exception): Handles the behavior of the exception, notifies the behavior of the exception
    • Catching exceptions: Handling the behavior of thrown exceptions

If an exception is thrown but not captured, the program stops moving at the exception breakpoint and notifies you of the exception.

9.31 keywords related to exceptions
    • @try: Defines the block of code used to test to determine whether to throw an exception
    • @catch: Defines the block of code used to handle thrown exceptions
    • @finally: code block executes whether or not an exception is thrown
    • @throw: Throwing Exceptions
9.32 catching different types of exceptions
    • Multiple @catch code blocks, processing code should be sorted in order from specific to abstract
9.33 Throwing Exceptions
    • When the program detects an exception, the exception must be reported to the code block that handles it
      • Use @ "Throw exception name"
      • Send a raise message to a NSException object
NSException *theException = [NSException exceptionWithName: ];
@throw theException; // throw an exception, can be used on other objects
[theException rasie] ;/ / throw an exception, raise is only valid for NSException object 

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Study note-objective-c] "objective-c-Basic Tutorial 2nd Edition" chapter Nineth memory Management

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.