Effective OC2.0 52 Reading notes (five memory management)

Source: Internet
Author: User

Fifth chapter: Memory management

29 Understanding reference Counts

30 simplifying reference counting with arc

Summary: Arc standardizes the memory management rules by naming conventions. Other programming languages rarely emphasize naming like OC. ARC replaces the direct invocation of autorelease and retain by setting a flag bit in the global data structure, which is specific to the processor for this data structure. This is the benefit of arc. Other optimization techniques will also occur when the compiler and runtime components are maturing. Corefoundation objects are not managed by arc, developers must call Cfretain/cfrelease as appropriate.

31 only release the reference and dismiss the listener in the Dealloc method

Summarize:

-(VOid) dealloc{

Cfrelease (Corefoundationobject);

[[Nsnotificationcenter Defaultcenter] removeobserver:self];

}

While it is said that references should be released in Dealloc, the overhead or scarce resources within the system are not. such as file descriptor (descriptor), socket (socket), chunk memory. It is not expected that Dealloc will be called at a particular time, because there are some unforeseen things that may also hold this object. The cleanup method should be called after the application has exhausted the resource object. You also need to call the cleanup method inside the-(void) Applicationwillterminate: (uiapplication *) application.

-(void) close{

_closed = YES;

}

-(void) dealloc{

if (!_closed = YES) {

NSLog (@ "Error:close is not called before Dealloc");

Sometimes you don't want to just output an error message, but throw an exception to indicate that not calling the Close method is a serious programming error

[Self close];

}

}

Although it is not necessary to invoke other methods in Dealloc, this is an exception to detecting programming errors.

Do not invoke the access method of the property in Dealloc, because someone might overwrite these methods and do some operations that cannot be performed safely during the recycling phase. In the Dealloc method, the thing to do is to release a reference to another object and cancel the notification of the original subscription's key-value observations or Nsnotificationcenter. If the object holds system resources such as file descriptors, a method should be written specifically to release this resource. Such classes are to be agreed with other users: The Close method must be called after the resource is exhausted. Methods that perform asynchronous tasks should not be called in Dealloc, and those methods that can only be executed in a normal state should not be called in Dealloc because the object is already in the state of being reclaimed.

32 attention to memory management issues when writing exception-Safe code

Summary: When catching exceptions, be sure to clean up the objects created within the try block. By default, ARC does not generate the cleanup code that is required to handle the exception safely. When the compiler flag is turned on, this code can be generated, but it can cause the application to become larger and reduce operational efficiency. Sometimes you need to catch and handle exceptions when you encode with oc++ or use a third-party library in your code and the exceptions thrown by this library are not under your control. If you manually manage reference counts and you must catch exceptions, try to ensure that the code is properly cleaned up. If you use arc and must catch an exception, you need to open the compiler's-fobjc-arc-exceptions flag. But most importantly, you should consider refactoring your code when you discover a large number of exception capture operations. Replace the exception with an nserror error message.

33 avoid retaining loops with weak references

Summary: Generally, if you don't own an object, don't keep it. This rule is an exception to collection, although collection does not directly own its content, but it wants to preserve those elements on behalf of the object to which it belongs. Sometimes a reference in an object points to another object that is not owned by itself. such as delegate mode. The automatic emptying of the weak reference is a new feature introduced with the arc, and is implemented by the run-time system. On weak references with automatic emptying, you can read their data at will, because this reference does not point to objects that have already been recycled.

34 to automatically release pool blocks to reduce memory spikes

Summary: Although the cost of automatically releasing pool blocks is not too high, there are still some, so try not to create an additional auto-release pool. The NSAutoreleasePool is more heavyweight and does not empty the pool every time a for loop is executed, and is typically used to create a pool that occasionally needs to be emptied. The auto-free pool block is more lightweight, and the auto-free pool can be established and emptied each time a loop is executed. The auto-free pool is arranged on the stack, and after the object receives the Autorelease message, the system puts it into the topmost pool. A reasonable use of the automatic release pool can reduce the memory spikes of the application. (need to consume a lot of resources, memory, CPU is the heavyweight, magnitude is mainly depends on the dependence of the container depends on, the smaller the dependence, the lighter the amount)

35 Debugging memory management issues with zombie objects

Summary: nszombieenabled = "YES", in fact, to do the Dealloc method of doing things, the runtime will dealloc into a zombie version. The system creates a corresponding new class for each class that becomes a zombie. When a message is sent to a zombie object, the system can then know which class the object belongs to. If all the zombie objects are grouped into the _nszombie_ class, the original class name is lost. The work of creating a new class is done by the run-time function Objc_duplicateclass (), which copies a copy of the structure of the entire _nszombie_ class and gives it a new name. The superclass of the replica class, the instance variables and methods are the same as before the copy. It is also possible to preserve the old class name by not copying _nszombie_ but by creating a new class that inherits from (lightweight) _nszombie_, but with the same function, it is less efficient than a direct copy. Since _nszombie_ does not implement any method, all messages sent to him go through the "full message forwarding mechanism". The object's ISA pointer is modified to point to a special zombie class, making the object a zombie object. The Zombie class responds to all the selectors. The response is: print a message containing the message content and its recipients, and then terminate the program.

36 Do not use Retaincount

Summary: Retain count never returns 0. The @ "somestring" retention count is 2 of the 64-1 @1 reserved count is 2 of 63-1 @3.141f. The reserved count of the Singleton object will never change, and the retention and release of this object are empty operations. Even between two singleton objects, their retention counts vary. Never use a retention count.

Effective OC2.0 52 Reading notes (five memory management)

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.