IOS Memory Traps

Source: Internet
Author: User

In the iphone development process, the memory leak in the code is easy to detect and change with the memory detection tool leaks, but some are due to the bug of iOS and usage error, leaks Detection tool can not detect, you will only see a lot of memory is used, Finally received didreceivememorywarning, eventually caused the program to crash. The following are some of the problems encountered in the development process and some information on the Internet, summed up:

First, [UIImage imagenamed:] Only suitable for reading with the map in the UI interface, larger resource files should be avoided as far as possible

The most common way to load local images with UIImage is the following three:

1. Using the Imagenamed method

[UIImage Imagenamed:imagename];

2. Using the Imagewithcontentsoffile method

NSString *thumbnailfile = [NSString stringWithFormat:@ "%@/%@.png"= [UIImage Imagewithcontentsoffile:thumbnailfile];

3. Using the Initwithcontentsfile method

UIImage *image = [[UIImage alloc] Initwithcontentsoffile:filepath]

The first method is a common method, which makes it easy to load resource images. When loaded in imagenamed, the image data is cached in system memory according to its name to improve the performance of the Imagenamed method to obtain the image object of the same image. This cache is not freed even if the generated object is Autoreleasepool released. and there is no clear method of release . If the image is larger, or the image is more, it consumes a lot of memory in this way.

The second method of loading the picture is not cached. The resulting object is autorelease when released when Autoreleasepool is released.

The third method is to manually release the drop. No system cache. Released immediately after release, generally used in the cover and other pictures of the larger place.

Second, the sliding list, the use of UITableView reuse mechanism

memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {           static@ "Cell";           *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];      if (cell = = nil)         {= [[[ UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:cellidentifier] autorelease];     
memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">

The Dequeuereusablecellwithidentifier method will reuse the hidden interface to save a lot of resources.

Third, to create a large number of local variables, you can create an embedded autorelease pool to release memory in a timely manner

memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">
int Main (intconstChar **pool = [[NSAutoreleasePool alloc] init]; int I, J;  for 0 ; i++*looppool =for0100000; J + + )    [nsstring stringWithFormat:@ "1234567890"]; // The resulting object is autorelease.  [Looppool release];} [Pool release]; return (0//  main
memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">

View more:iphone/mac objective-c Memory Management Tutorial and Principle Analysis (i) Fundamentals

Four, frequently open and close sqlite, resulting in a constant increase in memory

SQLite database is essentially a disk file, frequent open and close is very time-consuming and waste of resources, you can set the long way to connect sqlite; Avoid frequent opening and closing of the database ;

v. do not use the stringWithFormat method in the Cellforrowatindexpath agent of UITableView

There are many ways to define a string variable, the simplest of which is nsstring *str = @ "abc", and Initwithstring, stringWithFormat, stringwithcstring, and so on. When a large number of characters are manipulated, different methods consume different memory.

The following test code goes from: http://www.cocoachina.com/bbs/read.php?tid-17652-fpage-9.html

memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">
//test Machine 2.4 GHz Intel Core 2Duo 2GB 667 MHz DDR2 GCC 4.2
- (void) Teststringspeed: (ID) sender{NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init]; [TextField SetStringValue:@""]; inttesti,testnum=Ten; floatc,tm=0.0; for(testi=0; testi) {NSDate*beg=[NSDate Date]; inti,n=10000000; for(i=0; I){ //avg=0.030204 } C=[[NSDate Date] Timeintervalsincedate:beg]; TM+=C; [TextField setstringvalue:[nsstring stringWithFormat:@"%@\n%d=%f", [TextField stringvalue],testi+1, c]]; } [TextField setstringvalue:[nsstring stringWithFormat:@"%@\navg=%f", [TextField StringValue], (float) tm/Testnum]]; [Pool release];}
memory Trap "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif ">

Because stringWithFormat is time-consuming and memory-intensive, it consumes a lot of memory and time when Cellforrowatindexpath draws the cell, causing the interface to slide smoothly.

Vi. memory leaks about Colorwithpatternimage

Self.view.backgroundColor = [Uicolor colorwithpatternimage:[uiimage imagenamed:@ "bg.png" ]];

This method uses a picture to set the background color of the view, but some devices cause a memory leak, which can be viewed in detail:

http://blog.csdn.net/cococoolwhj/article/details/6942981

http://www.cocoaintheshell.com/2011/01/colorwithpatternimage-memory-usage/

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.