Objective-c Learning Notes _ memory management (i)

Source: Internet
Author: User


One, memory management of the type


Everyone has been to the library, and the books in the library can be borrowed. Let's imagine a scenario where everyone goes to borrow books, but no one has ever returned a book, so finally, the library will go bankrupt because there is no books to borrow, and everyone can no longer use the library. The same is true for computers, where the operating system reclaims the resources it consumes when the program finishes running. However, as long as the program runs, it consumes resources, and if you do not clean up unused resources, the resources will eventually be exhausted and the program will crash.



Learn memory Management We understand when you release objects and when you can't release them. The C language manages memory with malloc, Calloc, ReAlloc, and free. However, memory management in C is highly susceptible to memory leaks and wild pointer anomalies (the issue of C-language memory leaks, not the focus of Ben Boven, do not dwell too much on this.) Details will be devoted to the C memory issue in the following blog post. ), and Objective-c is optimized for this.



iOS apps appear crash (flashback), more than 90% of the reason is memory issues. In a project with several or even hundreds of classes, it is extremely difficult to find memory problems. Understanding Memory FAQs can help us reduce the chance of error. memory problems are manifested in two faces: memory overflow, wild pointer exception.



Memory overflow



iOS provides a certain amount of memory for each program, which is run on the program. iphone 3GS memory about 30M, iphone 5S memory 80M around. Once the memory limit is exceeded, the program is crash. The most memory in the program is the graph?、? frequency, video and other resource files. The 3.5-inch non-retina (retina) screen (320*480) puts a full-screen image, taking up bytes of 320*480*4 (4 bytes per pixel, storing rgba), i.e. 600k Bytes. The IPhone 3GS reads 60 images at the same time and crash. 4 inch screen (320*568), the actual pixel 640*1136, the program holds a full-screen picture, occupies the byte number 640*1136*4, namely 2.77M Bytes. The IPhone 5S reads 40 images at the same time and crash.



Wild Pointer exception



The object memory space has been reclaimed by the system and still has the pointer manipulate the memory. Wild pointer anomaly is the main reason of program crash. The more code the program, the harder it is to find the location of the wild pointer. Understanding memory management, can help us improve program performance, and greatly reduce debugging bug time.



Memory-Managed



Garbage Collection (GC): Programmers just need to open up memory space, do not need to be released in code display, the system to determine which space is no longer used, and reclaim these memory space in order to redistribute. The entire recycling process does not need to write any code, and the system automatically completes the garbage collection. In Java development, garbage collection technology has always been made.



Manual reference Count MRC (Manual Reference count): The opening and releasing of memory is controlled by the program code. Relative to garbage collection, the control of the memory is more flexible, can be released when the need to release, high demand for programmers, programmers should be familiar with the mechanism of memory management.



The dynamic reference count arc (Auto Reference count): Xcode4.2 and above has the automatic management of memory ARC mechanism, the compiler feature of IOS 5.0, which allows users to open only space without having to free up space. It is not garbage collected. The essence is MRC, but the compiler helps the programmer to add the freed code by default.



Memory Management for iOS


    • iOS supports two ways of managing Memory: ARC and MRC.
    • The MRC memory Management mechanism is: reference counting.
    • ARC is based on MRC.
Second, memory management mechanism and the method reference count that affect the reference count


In actual development, you may encounter more than two pointers using the same piece of memory. The C language cannot record the number of memory users. Objective-c uses a reference counting mechanism to manage memory, and when a new reference points to an object, the reference counter increments, and when a reference is removed, the reference count is decremented. When the reference count is 0 o'clock, the object frees the owning resource.


How to influence the counting of the citation?


+ alloc: Opens up memory space to make the reference count of the opened memory Space 1. This is the process from 0 to 1.



-Retain: The Count plus 1, if the memory space before the reference count is 1,retain to 2, if the reference count is 5,retain then becomes 6.



-Copy: Copies the contents of a memory area into a new memory space, the reference count of the copied area is unchanged, and the reference count for the new memory area is 1. Copy can understand that if pointer A and pointer b do not want to be involved with each other, a manages the memory of A, B manages B.



-Release: The reference count minus 1, if the memory space before the reference count is 4,release to 3, if the previous reference count is 1,release and then becomes 0, the memory is reclaimed by the system.



-Autorelease: A Moment in the future (the program runs out of the auto-free pool) reference count minus 1. If memory is still 4 after the reference count is 4,autorelease, it will change to 3 at some point in the future.



-Dealloc: A method inherited from a parent class that is automatically called by an object when the object reference count is 0. In the Dealloc method, the order of the variables is released in the reverse order of initialization, and in the final call [Super Init].



The Autoreleasepool?



Controls the release of Autorelease objects through Autoreleasepool.



Sends an AUTORELEASE message to an object, when the object is released, depending on the autoreleasepool.


NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Person * p = [[Person alloc] init]; // retainCount is 1
[p retain]; // retainCount is 2
[p autorelease]; // retainCount is 2 release sometime in the future
[pool release]; // Object reference count of autorelease at this time -1
NSLog (@ ”% d”, [p retainCount]); // prints 1


/ * NSAutoreleasePool running in ARC mode will get compilation errors instead of running errors. Instead, @autoreleasepool {} was introduced. This example is just a simple effect. * / 


NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];And[pool release];just like a pair of parentheses, [xxx autorelease]; must be written between the two. [xxx autorelease]; appears between the two, the pool will receive the object of Autorelease to save (in the way of the stack, the object into the stack) when [pool release]; The pool sends a release message to the previously saved object (the object is out of the stack, and the sooner the object is autorelease, the sooner the release message is received).



After iOS 5, it is no longer recommended to use the NSAutoreleasePool class, using @autoreleasepool{} instead. Previously written inNSAutoreleasePool *pool = [[NSAutoreleasePool
alloc] init];and[pool release];between the code, need to be written in@autoreleasepool{}the curly braces. Out curly braces, and automatically frees Chicai to send release messages to individual objects.


Three, the principle of memory management


The reference count increases and decreases equally, and when the reference count drops to 0, the memory space should not be made again. If you use Alloc, retain, or copy to increase the reference count of memory, you need to use release or autorelease to reduce the number of memory citation counts. Within a piece of code, the number of increments and decreases is equal.


Iv. Copy


Unlike retain, a copy of an object that wants to copy, needs to implement the Nscopying protocol and define the details of the copy (how to copy). If the class does not accept the Nscopying protocol and sends a copy message to the object, it causes crash.



Copy is divided into deep copy and shallow copy. We often use (including the example below) a shallow copy, as the difference will be described in detail in subsequent blog post.


The implementation of copy law


Person.h? Pieces


 
 
@interface Person : NSObject<NSCopying>

@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) int age;

@end


Person.m? Pieces


 
@implementation Person

- (id)copyWithZone:(NSZone *)zone

{
  Person *p = [[Person allocWithZone:zone] init];
  p.age = self.age;
  p.name = self.name;
  return p;
}


Main.m? Pieces


Person * p = [[Person alloc] init];
p.name = @ ”张三”;
p.age = 20;
Person * p2 = [p copy];
// p2 is a copy of p. p2.name is the same as p.name. p2.age is the same as p.age.


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



Objective-c Learning Notes _ memory management (i)


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.