25 Tips and tricks for enhancing the performance of iOS apps (beginner)

Source: Internet
Author: User
Tags gcd uikit

25 tips and tricks for enhancing the performance of iOS apps (beginner)Tags: iOS memory management performance optimization2013-12-13 10:53 916 people read Comments (0) favorite reports Classification:iphone Development Advanced Series

When developing an iOS application, it is critical that your program has good performance. This is also what users expect, if your program runs slow or slow, will incur the user's bad comment. However, due to the limitations of iOS devices, sometimes you want to get good

"" Reading device

When developing an iOS application, it is critical that your program has good performance. This is also what users expect, if your program runs slow or slow, will incur the user's bad comment. However, due to the limitations of iOS devices, it is sometimes difficult to get good performance. There are a lot of things to keep in mind during the development process, and it's easy to forget about the performance impact.

This article collects 25 tips and tricks for improving program performance and divides performance optimization techniques into 3 different levels: Beginner, intermediate, and advanced

Primary

In the development process, the following primary techniques need to be noted at all times:

1. Using Arc for memory management
2. Use of reuseidentifier in appropriate cases
3. Set the view to opaque (Opaque) whenever possible
4. Avoid bloated xibs
5. Do not block the main thread

6. Make the picture the same size as Uiimageview
7. Select the correct collection
8. Using gzip compression

1) Use ARC for memory management

The arc was released in iOS 5, which addresses the most common memory leaks – and is the easiest for developers to forget. ARC's full name is "Automatic Reference counting"-automatic reference counting, it will automatically do retain/release work in the code, developers do not have to manually handle.

Here are some code blocks for creating a view generic:

    1. UIView *view = [[UIView alloc] init];
    2. // ...
    3. [Self.view Addsubview:view];
    4. [View release];

It is easy to forget to call release where the above code ends. However, when using ARC, ARC will automatically call release for you in the background.

In addition to avoiding memory leaks, ARC helps improve program performance: Arc automatically destroys objects when objects in the program are no longer needed. So, you should use arc in your project.

Here are some resources to learn about arc:

Apple's official documentation


Matthijs Hollemans's primary arc


Tony Dahbura How to use arc in a cocos2d 2.X project


If you're still unsure about the benefits of arc, look at some of this article: 8 Myths about arc--which can make you believe you should use arc! in your project


It should be noted that ARC does not prevent all memory leaks. There may be memory leaks in the project after using ARC, but the main reasons for these memory leaks are: Block,retain loops, mismanagement of corefoundation objects (usually C structures), and really code not being written well.


Here's an article that explains what issues arc can't solve-and how to deal with them.

2) Use Reuseidentifier in appropriate cases


Use Reuseidentifier in the appropriate situation
A common mistake in developing iOS programs is not to set the reuseidentifier correctly for Uitableviewcells, Uicollectionviewcells, and Uitableviewheaderfooterviews.

For best performance, when a cell is returned in the Tableview:cellforrowatindexpath: method, the data source for table view generally reuses the UITableViewCell object. Table view maintains a queue or list of UITableViewCell objects that have been marked for reuse.

What happens if I don't use reuseidentifier? If you do not use Reuseidentifier,table view in your program each time you display a row, you will configure a new cell. This is actually a very resource-intensive operation and can affect the efficiency of the table view scrolling in the program.

Since iOS 6, you may also want headers and footer views, as well as Uicollectionview cell and supplementary views.

In order to use Reuseidentifiers, when a table view requests a new cell, the following method is called in the data source:

    1. static NSString *cellidentifier = @"Cell";
    2. UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier Forindexpath:indexpath];

If the table view maintains a uitableviewcell queue or a cell in the list that is available, a new cell is removed from the queue from the existing cell, or, if not, from the previously registered nib file or class. If there is no cell that can be reused, and the nib file or class is not registered, TableView's Dequeuereusablecellwithidentifier: method returns a nil.


3) Set the view to opaque (Opaque) whenever possible


Try to set the view to opaque

If the view is opaque, then its opaque property should be set to Yes. Why did you do it? This setting allows the system to draw the view in an optimal way. The opaque property can be set in Interface Builder or code.

Apple's Official document has the following explanation for the opaque attribute:

The provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some Drawin G Operations and improve performance. If set to NO, the drawing system composites the view normally and other content. The default value of the IS YES.

(The Opaque property hints at how the system handles view.) If opaque is set to Yes, the drawing system will see view as completely opaque, so the drawing system can optimize some of the drawing operations to improve performance. If set to no, the drawing system handles the view in conjunction with other content. By default, this property is yes. )

If the screen is still, the setting of this opaque property is not a big problem. However, if the view is embedded in scroll view, or is part of a complex animation, setting this property will certainly affect the performance of the program! You can see which view is not set to opaque through the emulator's Debug\color blended layers option. For the performance of the program, set the view as opaque as possible!

4) Avoid bloated xibs


Avoid bloated xibs.

Start using storyboards in iOS 5, and will replace Xibs. In some cases, however, xibs is still useful. If your program needs to run on a device that has a previous version of iOS 5, or if you want to customize a reusable view, it's unavoidable to use Xibs.

If you have to use xibs, try to make the Xibs file simple. And each view controller for a xib file, if possible, a view controller's view of the different layers of separate into a xibs file.

(Note: When a xib file is loaded into memory, everything in the Xib file is loaded into memory, including pictures.) If a view is not being used immediately, it can cause a waste of memory. This does not happen in storyboard, because storyboard also instantiates a view controller when needed. )

When loading xib, all the images involved will be cached, and if the program is developed for OS X, the sound file will be loaded. Apple's official documents say this:

When you load a nib file of contains references to image or sound resources, the nib-loading code reads the actual image or sound file into memory and and caches it. In OS X, the image and sound resources is stored in named caches so, the can access them later if needed. In IOS, only image resources is stored in named caches. To access images, you use the Imagenamed:method of nsimage or UIImage and depending on your platform.

(When a nib file is loaded, the picture or sound resource involved in the nib file is also loaded into memory, and the Nib-loading code reads the actual picture or sound file into memory and caches it all the time.) In OS X, both picture and sound resources are stored in the named cache, which can then be accessed if needed. In iOS, only picture resources are stored in the named cache. To access the picture, use the Nsimage or UIImage (depending on the system) of the Imagenamed: method. )

It is clear that similar cache operations occur when using storyboard, but I have not found any information about the content. Want to learn more about storyboard? You can look at Matthijs Hollemans written in iOS 5: Beginner Storyboard Part 1 and Part2.

5) do not block the main thread


Never do heavy tasks on the main thread. Because Uikit's left and right tasks are performed in the main thread, such as drawing, touch management, and input responses.

The risk of doing all tasks on the main thread is that if your code blocks the main thread, the program will become unresponsive. This time the user in the App Store on the program's bad reviews!

In most cases where I/O operations are performed, the main thread of the ancestor plug is to read and write external resources, such as disks or networks.

About network operations can be performed asynchronously using the following methods of Nsurlconnection:

    1. + (void) Sendasynchronousrequest: (nsurlrequest *) request queue: (Nsoperationqueue *) queue Completionhandler: ( void (^) (nsurlresponse*, nsdata*, nserror*)) handler

Or use a third-party framework, such as afnetworking.

If you need to do some other type of expensive operation (such as performing a time-intensive calculation or reading and writing to a disk), use GCD (Grand Central Dispatch), or Nsoperations and nsoperationqueues.

The following code is a template that uses GCD:

    1. Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
    2. //switch to a background thread and perform your expensive operation
    3. Dispatch_async (Dispatch_get_main_queue (), ^{
    4. //Switch back to the main thread to update your UI
    5. });
    6. });

As the code above, why is there a dispatch_async nested inside the first dispatch_async? This is because the code related to Uikit needs to be executed in the main thread.

You can look at the tutorials in Ray Wenderlich: Multithreading and gcd-Beginner in iOS, and how Soheil Azarpour uses Nsoperations and nsoperationqueues tutorials.

6) make the picture the same size as Uiimageview


Make sure the picture and Uiimageview are the same size
If you need to display the pictures in the program bundle to Uiimageview, make sure the picture and Uiimageview are the same size. Because the scaling of pictures is very resource intensive, especially embedding Uiimageview into Uiscrollview.

If you download a picture from a remote service, sometimes you can't control the size of the image, or you can't zoom the image on the server before downloading it. In this case, when the picture is finished downloading, you can manually zoom the picture--do it in the background thread! --and then use the picture in the Uiimageview.


7) Select the correct collection


Select the correct collection
Learning to use the most appropriate class or object is the basis for writing efficient code. This is especially important when working with collection data.
Apple's official website has an article on the collection Programming theme (Collections programming Topics)--A detailed description of the classes that can be used in the collection data, and what classes to use in which case. When working with collections, each developer should read this document.
Too long to read (TLDR)? Here is an introduction to the Common collection types:
• Array: is a list of values sorted in order. Depending on the index, you can find it quickly, but it's slower to find it by value, and it's slower to insert and delete.
• Dictionary: Store key/value pairs. You can find it quickly by key.
sets: is a list of unordered values that can be quickly found based on values, and also faster to insert and delete.

8) Use gzip compression


Using gzip compression


More and more programs rely on external data, which typically comes from remote servers or other external APIs. Sometimes you need to develop a program to download some data, which can be xml,json,html or some other text format.

The problem is that the network on the mobile device is not deterministic. The user's device may be in the edge network for one minute, then then in the 3G network. No matter what the situation, don't let the user wait.

There is an optimized choice: use gzip to compress the data in the network transmission, which reduces the size of the file and speeds up the download. Compression is especially useful for text data because the text has a high compression ratio.

In iOS, if you use Nsurlconnection, gzip compression is already supported by default, and Nsurlconnection-based frames pages support gzip compression, such as afnetworking. Even some cloud service providers have delivered compressed responses, such as Google App Engine.

Here's an article on gzip compression that explains how to turn on support for gzip compression in Apache live IIS server.

25 Tips and tricks for enhancing the performance of iOS apps (beginner)

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.