OBJ-C Memory Management Primary

Source: Internet
Author: User

Primary Memory Management Why to manage memory

Our iOS APP appears crash (Flash back), more than 90% of the reason is memory problems. One of the exc_bad_access problems we often see when compiling a run with Xcode is a typical memory error--Accessing a piece of zombie memory, which of course does not have an in-depth discussion of zombie memory. So what are the main aspects of memory problems, that is, "memory overflow" and "Wild Pointer exception".

Memory overflow

iOS gives each program a fixed amount of memory, which is the program's delivery? iphone 3GS memory about 30M, iphone 5S memory 80M around. If the memory limit is exceeded, the program will crash.

  The most memory in the program is the graph?、? frequency, video and other resources. 3.5?? The Retina screen (320*480) put the Zhang Quan figure, the number of bytes 320*480*4 (4 bytes, storage of RGBA), that is: 600k Bytes. IPhone 3GS reads 60 pictures at the same time, it will crash.

4. Screen (320*568), actual pixel 640*1136, program storage Zhang Quan Chart, the number of words 640*1136*4, that is, 2.77M Bytes. IPhone 5S reads 40 pictures at the same time, it will crash.

So beginners in the development of the app, the use of pictures must be cautious, pay attention to performance.

Wild Pointer exception

The object memory space has been reclaimed by the system and still has the pointer manipulate the memory. The anomaly of wild finger needle is the main reason of program crash. The more code the program, the harder it is to find out where the wild pointers appear.

Introduction to the main methods of memory management

Garbage collection (GC): Java;

in the garbage collection mechanism , programmers only need to open up memory space, do not need the code to release, the system to determine which space is no longer being made, and reclaim these memory space in order to allocate again. The entire recycling process does not need to write any code, and the system completes the garbage collection. In Java development, it is the garbage collection technology that makes it straight.

OC has also a GC mechanism, but is disabled by Apple after iOS and Mac OS 10.4.

Manual reference Count MRC (Manual Reference count):

memory opening and release are controlled by program code. relative to garbage collection, the control of the memory more flexible, can be released in time when the need to release, more requirements for programmers, programmers should be familiar with the mechanism of memory management.

Features: More flexibility in relative GC memory control, high programmer requirements

Auto Reference count arc (Auto Reference count):

the compiler feature of IOS 5.0 allows users to open only space without freeing up space. But arc is not garbage collection! It is still the MRC, but the compiler helps the programmer to add the release code by default.

OC Memory Management mechanism

In the C language, we use malloc and free to manage the creation and deallocation of heap memory. Heap memory is also only being used and destroyed in both of these states. However, in the actual development, we may encounter more than two pointers pointing to the same piece of memory, the C language can not record the number of memory users. The reference counting mechanism used in obj-c is a good solution to this problem.

  OC-Citation counting mechanism manages memory when a new citation is directed to an object? The counter is incremented, and when the citation is removed, the count is decremented. When the citation is counted to zero, the object will release the owning resource.

Methods that affect reference counting

+ Alloc: To open up memory space, let the open memory space reference count +1, this is the process of 0 to 1.

(The memory space is only opened when you see ALLOC),

Instance variables cannot be used in class methods, instance methods cannot be invoked because no memory space has been opened

-Retain: Reference count plus 1 returns the object itself

-Copy: Copying the contents of a memory area? Copy, cuff? To the new memory space? To the original copy of the area of the index, the new memory area of the citation count is 1.

-Release: Citation Count minus 1. Release after release with nil use can be safely released.

-Dealloc: A method inherited from a parent class that is automatically called by an object when the object reference count is 0 o'clock.

-Autorelease: In Autoreleasepool, retain minus 1 is not executed immediately.

The following is a code example demo, just to list the knowledge points, if you do not comment some code blocks may not run:


#import<Foundation/Foundation.h>#import "Person.h"#import "Student.h"#defineRelease_safe (_point) [_point release];_point = nil;intMainintargcConst Char*argv[]) {    //Auto Free Pool//is a stack structure, and whenever you encounter a autorelease, put him in the stack.//when an auto-free pool is released, all object reference counts in the stack are reduced by one@autoreleasepool {//the reference count for P1 is 1Person *P1 =[[Person alloc] init]; NSLog (@"%ld", [P1 retaincount]); //retainPerson *P2 =[P1 retain]; NSLog (@"%ld", [P2 retaincount]);//Person *p3 = [P1 copy];//NSLog (@ "%ld", [P3 Retaincount]);[P1 release]; NSLog (@"%ld", [P1 retaincount]);        [P2 release]; //Retaincount does not record 0NSLog (@"%ld", [P2 retaincount]); //reference count is 1Person *P1 =[[Person alloc] init]; //reference count is 2Person *P2 =[P1 retain]; //reference count is 1[P1 release]; //Safe ReleaseP1 =Nil; //reference count is 0//This release has no effect .[P1 release]; //safe and easy to free space with the use of parametric macrosRelease_safe (p2); person*P1 =[[Person alloc] init]; person*P2 =[[Person alloc] init]; P1.name=@"Pommeron"; P1.books= @[@"100,000 Cold Jokes",@"dead brother ."]; //[P1 retain]; //Autorelease does not immediately reduce the reference count by one//after leaving the auto-free pool, the reference count is reduced by one[P1 autorelease]; [P2 autorelease];//NSLog (@ "%ld", [P1 retaincount]);             }    //usually one alloc, supporting one release or Autorelease//usually one retain, supporting one release or Autorelease//one copy at a time, supporting a release or Autorelease//who pollutes who governs Person*P1 =[[Person alloc] init]; person*P2 =[P1 copy]; P1.name=@"such as Flowers"; P2.name=@"Iron Pillar"; NSLog (@"%@", P2.name);    Release_safe (p2);    Release_safe (p1);      [P1 copy]; Student*S1 =[[Student alloc] init]; S1.name=@"Xuesheng"; S1.age=1; person*S2 =[S1 copy]; S2.name=@"Taibao"; NSLog (@"%@", S1.name);    Release_safe (S2);   Release_safe (S1); /*     * It is not recommended to use instance objects to establish autoreleasepool */NSAutoreleasePool*pool =[[NSAutoreleasePool alloc] init]; //pool area, no scope problem, autorelease objects need to use secure releasePerson *P1 =[[Person alloc] init];    [P1 autorelease];    [Pool release]; Pool=Nil; P1=Nil; return 0;}


#import <Foundation/Foundation.h>@interface person:nsobject<nscopying>*  *books; @end


#import "Person.h"@implementation Person//destroying Objects- (void) dealloc{//the Dealloc method is called automatically when the object reference count is 0 o'clockNSLog (@"Ah, I ' m over!"); //clear the memory that your instance variable points to before destroying an object[_name release];        [_books release]; //finally destroys something inherited from the parent class.[Super Dealloc];}- (ID) Copywithzone: (Nszone *) zone{//Shallow Copy//return [self retain]; //Deep CopyPerson *p =[[Person Allocwithzone:zone] init]; P.name= [NSString stringWithFormat:@"%@", Self.name]; P.books=[Nsarray arrayWithArray:self.books]; returnp;}@end


#import <Foundation/Foundation.h>@interface student:nsobject<nscopying>  *name; @property (nonatomic,assign) Nsinteger age; @end


  #import  "     @implementation  Span style= "color: #000000;" > Student -(void  ) dealloc{[_name Release    ]; [Super Dealloc];}  -(id ) Copywithzone: (Nszone *) zone{Student     *s = [[Student Allocwithzone:zone] init]; S.name  = [nsstring stringwithformat:@ " %    @   ,_name];    S.age  = _age;  return   S;}   @end  

Autoreleasepool is a stack space

Memory Management Principles

Usually one alloc, supporting one release or autorelease

Usually one retain, supporting one release or autorelease

One copy at a time, supporting a release or autorelease

Who Pollutes who governs

OBJ-C Memory Management Primary

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.