iphone Development Memory Management

Source: Internet
Author: User
Tags count garbage collection memory usage

It's not hard to develop an iphone app, it's basically three words-"memory, Memory, memory." The IPhone OS requires very strict memory, memory leak, kill; The memory uses the super limit, kills off. A tested program, during the use of more than 90% of the crash is caused by memory problems. Here's a quick summary of object-c memory management.

Basic concepts

Object-c's memory management is a very common technique based on reference counting (Reference count). Simply put, if you want to use an object and want to make sure that the object is not freed during use, you need to get "ownership" through a function call, and then call the function to release "ownership" after the end of the use. The acquisition and release of "ownership", the increase and decrease of the reference count, the representation of the object and the reference when a positive number, and the free representation of the zero.

Function

The functions that get ownership include

Alloc-Create object is call Alloc, allocate memory for object, object reference count plus one.

Copy-Copies an object, returns a new object, references the Count plus one.

Retain-reference count plus one to get ownership of the object.

In addition, functions with Alloc, copy, and retain strings in the name are also considered to be the reference count plus one.

Functions that release ownership include

Release-reference count minus one, releasing ownership. If the reference count is reduced to zero, the object is freed.

Autorelease-Release at some time in the future. The following is a specific explanation.

Autorelease

In some cases, you do not want to take ownership, and you do not want the object to be freed. For example, in a function to generate a new object and return, the function itself does not want to take ownership, because there is no opportunity to release after the acquisition (unless the creation of a new calling rules, and the call rule is the beginning of all chaos), and can not be released within the function, with the help of Autorelease The so-called autorelease can be understood to give all power to an external system (the system is actually called Autorelease Pool), which manages the release of the object. Objects assigned to Autorelease are generally considered valid in the current event loop. You can also create your own nsautoreleasepool to control the autorelease process.

According to Apple's people say, autorelease efficiency is not high, so can own release place, as far as possible own release, do not hand over to autorelease to deal with.

Rules

The reference counting system has its own rules of reference, and you can follow the rules with fewer errors:

The function to get ownership corresponds to the function one by one that frees ownership.

It is guaranteed that only functions with Alloc, copy, and retain strings will allow the caller to take ownership, i.e. reference count plus one.

Frees the instance variables owned by the object in the object's Dealloc function.

Never directly call Dealloc to free an object and completely rely on reference counting to complete the release of the object.

There are many classes that provide convenient constructors (convenience constructors) that create objects without adding reference counts, meaning that you do not need to call release to free ownership. Well recognizable, there will be no alloc and copy in their names.

By complying with these rules, you can basically eliminate any memory leaks that intrument can discover.

Container

Classes such as Nsarray, Nsdictionary, Nsset, and so on, take ownership of a reference count plus a title after an object is added, freeing the object in the container when the object is removed or the entire container object is released. A similar situation is UIView's ownership of Subview, Uinavigationcontroller the ownership of controller on its stack, and so on.

The generation of other ownership

There are also usages that allow the system to have ownership of objects. Like NSObject's performSelector:withObject:afterDelay. If necessary, the call that needs to be displayed is cancelPreviousPerformRequestsWithTarget:selector:object:, otherwise it is possible to generate a memory leak.

Leaks due to this cause do not violate any rules, it is intrument can not find.

Circular Reference

All reference counting systems are subject to cyclic application. For example, the following reference relationship:

Object A is created and referenced to object B.

Object B is created and referenced to object C.

Object C is created and referenced to object B.

The reference count for B and C is 2 and 1, respectively. When a no longer uses B, call release releases the ownership of B, because C also references B, so B's reference count is 1,b and will not be released. B is not released, the reference count of C is 1,c and will not be released. From then on, B and C remain in memory forever.

In this case, you must interrupt the circular reference and maintain the reference relationship through other rules. For example, our common delegate tend to be the attributes of the Assign method rather than the Retain method, and the assignment does not increase the reference count to prevent unnecessary circular references at both ends of the delegation. If a Uitableviewcontroller object a takes ownership of UITableView object B through retain, the delegate of this UITableView object B is a, if the delegate is retain way, There's basically no chance of releasing these two objects. You should also pay attention to this when you design and use the delegate mode.

Memory leaks due to circular references are also instrument, so be especially careful.

Some useful content related to memory management:

Objective-c2.0 claim to be able to support the garbage collection, that is, garbage collection, but I have not found in the Xcode and documents related usage, also lazy to check. About the content of garbage collection also have nothing to say, want to talk about these days without GC case of several memory related problems.

Objective-c's autorelease did give development a lot of work to improve development efficiency, which is fine for Mac OS X desktop development because there is no memory tension in memory. But if you want to develop a program for the iphone, or use autorelease good, otherwise have to wait for the program to exit and then clean up the memory. It's best not to save unwanted objects on the iphone, and create them when you use them, such as pictures, files, and so on. There is also a point to note is UITableView, if you are put UITableView in the Uitableviewcontroller, then don't worry, no problem, if you are in Uiviewcontroller or its subclasses to place UITableView, then notice, in pop off Viewcontroller must remember to set the UITableView delegate to empty, that is, [TableView Setdelegate:nil], because TableView's delegate is a retain that saves objects, so if you don't set delegate to nil before POPs, you won't call view Controller of the Dealloc, memory can not be released, so a few of the memory will be tight.

Summarizes a few memory usage experiences

1. Object is now created

2. All objects created with alloc,new, retain and so on need to call release to free, do not send releases message to Autorelease object, otherwise only over the

3. Note delegate, if retain type, it is best to set it to nil before releasing it

4. Create your own nsautoreleasepool in places where you frequently use alloc (loops)

5. For UIImage objects use [uiimage imagenamed:], use [uiimage imagewithcontentoffile:] or [image initwithcontentoffile:]

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.