"Original" Do you really know the autorelease of iOS?

Source: Internet
Author: User

=======================================================

Original articles, reproduced please indicate the program small Weng @ Blog Park, Mail [email Protected],jilon, welcome you and I in the c/c++/objective-c/machine vision and other fields to start communication!

=======================================================

Perhaps this topic is a bit too high-profile, but I just want to correct some of the children's shoes for autorelease, if can help a few people, then this article is worth it! Of course, master, please take a detour

This paper mainly discusses two aspects:(1) Autorelease object is suitable to be deconstructed? (2) How does OC handle an object that has been autorelease out?

(1) is the Autorelease object suitable to be deconstructed?

The problem is not difficult to say, but it is not easy to say simple. Let's start by looking at a familiar code that you can no longer understand:

1 -(void) viewdidload {2    [Super Viewdidload]; 3     Nsarray *localarr = [Nsarray arraywithobject:@ "Weng zilin"]; // This is a local object that encapsulates the Autorelease method
4 }

Excuse me, when is this local variable Localarr? Many people will answer: "Out of scope, that is, after the curly braces will be recycled." But unfortunately, the truth is not as smooth as you think. Here's a few lines of code to prove to you that Localarr is still alive and well: (under the ARC environment)

__weakIDObjtrace;- (void) viewdidload {[Super viewdidload]; Nsarray*localarr = [Nsarray arraywithobject:@"Weng Zilin"];//This is a local object that encapsulates the Autorelease method}- (void) Viewwillappear: (BOOL) animated{[Super viewwillappear:animated]; NSLog (@"viewwillappear__localarr:%@", Objtrace);}- (void) Viewdidappear: (BOOL) animated{[Super viewdidappear:animated]; NSLog (@"viewwillappear__localarr:%@", Objtrace);}

In the ARC environment I use a __weak type to track Localarr release time, __weak does not increase the reference count for Localarr, so it does not interfere with its release, the log is displayed as follows:

We found that Localarr in Viewwillappear is still alive, in Didappear has been hung. This illustrates one thing: Autorelease does not decide to release the opportunity according to the scope. What is it based on? The answer is: Runloop. Runloop is not in the scope of this article, interested students please consult the information themselves, the portal point here. Simply put, Runloop is the message loop mechanism in iOS, and when a runloop ends, the system cleans up objects that were autorelease processed at once. Essentially, the object that was placed in the Autorelease pool during this iteration was cleared at the end of the runloop iteration. As to when Runloop ended and there was no fixed duration!

So the question is: Is this runloop-based memory recycling strategy for iOS inconvenient? I think it's obvious. Whenever things always have two sides, the use of autorelease is really convenient, but under certain circumstances will bring performance problems. Let's take a look at this example, reproduced in my previous article:

 for(inti =0; I <= +; i + +) {       //1. First we get the path to the image resource that needs to be processedNSString *filepath = [[NSBundle mainbundle] Pathforresource:@"Test"OfType:@"PNG"]; //2. Load the image into memory, we use the ALLOC keyword, after use, you can quickly release the memory manuallyUIImage *image =[[UIImage alloc] initwithcontentsoffile:filepath]; //3. In this step we compress the image and get an instance of the Autorelease typeSelf.image2 = [Image Imagebyscalingandcroppingforsize:cgsizemake (480, the)]; //4. Release 2 Steps of Memory[Image release]; }

The above example does not seem to be a problem because everything is done in accordance with MRC's rules, which can be said to be a very normative notation. But mostly to the Image2 object. The temporary image object assigned to the Image2 object is a autorelease type. Actually running this program will find that the memory continues to rise in the loop 1000 times because the Autorelease object is not released as we expected at the end of the curly brace for each for loop! It would be reasonable to consider it from the perspective of Runloop.

Then the question comes again: since handing over to runloop treatment is not reassuring (Runloop actually has human "procrastination disease"), then we can manually intervene Autorelease object release time? The answer is, a rapturous, yes. The above mentioned Autorelease pool, this is the next problem to solve the task, do not expand here, you just need to know, once an object is Autorelease, then the object will be placed in a pool of iOS: Autorelease pool, In fact, the pool is essentially a stack, and the object thrown into the pool is equivalent to the stack. We put the code blocks that needed to be released in time into our generated autorelease pool, emptied the custom pool, and actively emptied the pool to allow the memory to be freed up in time. For example, the image processing example above is optimized as follows:

1  for(inti =0; I <= +; i + +) {2  3        //Create an auto-free pool4NSAutoreleasePool *pool = [NSAutoreleasePoolNew];//can also use @autoreleasepool{domesomething} in the same way5NSString *filepath = [[NSBundle mainbundle] Pathforresource:@"Test"OfType:@"PNG"];6UIImage *image =[[UIImage alloc] initwithcontentsoffile:filepath];7UIImage *image2 = [Image Imagebyscalingandcroppingforsize:cgsizemake (480, the)];8 [Image release];9        //Frees the pool memory automatically, releasing the temporary variables generated in the code above Image2Ten [Pool drain]; One}

The operation of the pool can also be used equivalently to @autoreleasepool{domesomething;} Alternative. The above is a brief answer to the first question thrown at the beginning of this article, summary is: The release time is based on runloop rather than the scope, through the Autorelease Pool manual intervention release, loop multiple times, be careful to optimize the autorelease. Let's start with a second discussion.

(2) What is the process after an object has been marked as autorelease?

In fact, I think this problem is more interesting to discuss, because it has been compared to the bottom. The first mentioned Autorelease object is finally put into the autorelease pool, then what is this pool sacred? When we use @autoreleasepool{}, the compiler actually translates it into the following code:

void *context = objc_autoreleasepoolpush (); // Code Objc_autoreleasepoolpop (context) in {} ;//pop operation at the end of the current runloop iteration

And what about Objc_autoreleasepoolpush and Objc_autoreleasepoolpop? They're just a simple package for autoreleasepoolpage, here is the structure of the autoreleasepoolpage, which is a C + + data type, essentially a doubly linked list. Next is the next position that points to the top of the current stack.

There are a variety of parameters, but remember this sentence: to send a message to an object is to add - autorelease this object to the current autoreleasepoolpage stack top next pointer to the location.

At the end of the article, incidentally, there are three common traversal methods in iOS: For, Forin, Enumerateobjectsusingblcok. The actual use of people may not feel what difference, the first two more commonly used, the last one is the unique way of the iOS traversal, but in fact there is a difference. Block version of the traversal has been embedded in the @autoreleasepool{} operation, and the previous two no, which means that the use of block version of the traversal will make the app more robust, more efficient use of memory, and, forcing a higher, hey!

The discussion of this article is here, that's all.

Reference:

http://blog.sunnyxx.com/

Http://www.cnblogs.com/wengzilin/p/3301549.html

Http://www.cnblogs.com/xwang/p/3547685.html

"Original" Do you really know the autorelease of iOS?

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.