IOS --- automatically release the pool

Source: Internet
Author: User

IOS --- automatically release the pool
Auto Release pool

  • In mrc Code, there is no weak and only assign
  • The assign modifier does not perform any operations on the object, but simply records the address.
  • Weak is exclusive to ARC. If the object does not have any other objects for strong reference, it will be released immediately!
  • Weak is very inefficient!
  • The assign records the address. After the object is released, the address is retained. During MRC development, wild pointer errors are very frequent.
  • Weak is safe! Once there is no strong reference, the address is automatically set to nil, OC can send any message to nil will not be wrong!

  • The role of autorelease isDelayed releaseTo add a delayed release tag to the object.

    Automatic release object atuorelease automatic release object
    • All "autorelease" objects are automatically added to the "recently created" Auto Release pool after they are out of scope!
    • When the automatic release pool is destroyed or used up, a release message is sent to all objects in the pool to release the objects in the pool.
    • Automatically release the pool, which is also valid in the ARC & MRC program! Test System variables in MRC

      Declare Variables

      @property (nonatomic, assign) UIButton *btn;

      Add button to Controller View:

      // Alloc/init-it should be out of scope before it will be released // self. btn = [[UIButton alloc] init]; self. btn. frame = CGRectMake (40, 40,100,100); self. btn. backgroundColor = [UIColor orangeColor]; [self. view addSubview: self. btn]; NSLog (@ "% @", self. view. subviews); // The class method created is 'autorellimit' // out of scope, will be added to the automatic release pool // before the automatic release pool is destroyed, to release the object! Self. btn = [UIButton buttonWithType: UIButtonTypeContactAdd]; [self. view addSubview: self. btn]; NSLog (@ "% @", self. view. subviews); // The drill above is difficult! Mainly weak!

      Running result:

      10:31:20. 055 09-automatic release pool [27279: 718327] ("<_ UILayoutGuide: 0x7fc5d0d1_b0; frame = (0 0; 0 0); hidden = YES; layer =
            
             
      > "," <_ UILayoutGuide: 0x7fc5d0e77950; frame = (0 0; 0 0); hidden = YES; layer =
             
              
      > ","
              
               
      > ") 10:31:20. 063 09-automatic release pool [27279: 718327] ("<_ UILayoutGuide: 0x7fc5d0d1_b0; frame = (0 0; 0 0); hidden = YES; layer =
               
                
      > "," <_ UILayoutGuide: 0x7fc5d0e77950; frame = (0 0; 0 0); hidden = YES; layer =
                
                  > ","
                 
                   > ","
                  
                    > ")
                  
                 
                
               
              
             
            

      We can see that both alloc and buttonWithType can be added to the Controller's View, which means that the created button is not destroyed immediately.

      • The variables declared by assign, after alloc, the object will not be released immediately and will be destroyed only by the scope. Even after the object is destroyed, the address of the assign record will not be cleared, which can easily causeWild pointerError
      • Using buttonWithType: The created object will not be released immediately. The system class method creates the object, which is the defaultautorealease, Out of scope, will be customized to addAuto Release poolThe object will be released only after the pool is automatically released and destroyed. Similarly, the variables declared by assign will hold the address of the object and will not be released ~ Automatic release of custom objects in MRC

        Person. h

        @interface Person : NSObject+ (instancetype)person;@end

        Person. m

        • Note: autorelease is not added here.
          @ Implementation Person + (instancetype) person {// autorelease is used for delayed release // Add the Person * p = [[Person alloc] init] to the object; return p;}-(void) dealloc {NSLog (@ "I 've gone"); [super dealloc] ;}@ end

          Declare the Persion variable:

          @property (nonatomic, assign) Person *p;

          Test Demo:

          - (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    self.p = [Person person];    NSLog(@"%@", self.p);}

          Running result:

          10:44:16. 652 10-ARC automatic release [27546: 726446]
                    
          Summary:

          In MRC, if the provided class method does not have autorelease, the address of the object will still be printed when the assign variable is received during the call. Of course, the object is not destroyed (Dealloc no output).

          Add the class method with autorelease
          Person *p = [[[Person alloc] init] autorelease];

          Print result:

          10:56:04. 224 10-ARC automatic release [27690: 732059]
                    
                     
          10:56:04. 238 10-ARC automatic release [27690: 732059] I went
                    

          We can see that the object has been released, indicating that autorelease has addedDelayed releaseSo that the object is automatically released when the release pool is automatically destroyed, or when the automatic release pool scope is closest to it.

          Automatic release in ARC

          Variable declaration:

          @property (nonatomic, weak) Person *p;@property (nonatomic, weak) UIButton *button;

          Test Demo:

          // In ARC, if you set the alloc/init value for weak, Xcode will prompt you! Self. p = [[Person alloc] init]; // For the Xcode compiler, as long as it is a class method, no prompt will be prompted! // If MRC is used for development, all class methods that return instancetype will return autorelease objects! // Because there is no strong reference, the self. p = [Person person Person] will be released immediately; // The reason why the parameter is null in ARC is that weak has nothing to do with autorelease! NSLog (@ "% @", self. p); // This is because the bottom layer of the apple framework is written in MRC, and the objects returned by buttonWithType contain autorelease self. button = [UIButton buttonWithType: UIButtonTypeContactAdd]; NSLog (@ "% @", self. button );

          Print result:

          11:00:58. 756 10-ARC automatic release [27778: 735123] (null) 11:00:58. 769 10-ARC automatic release [27778: 735123]
                    
                     
          >
                    
          Summary
          • If the alloc of a common object and the object is weak, Xcode will automatically warn you that the object will be destroyed once it is created.
          • However, if you provide a class method, you can quickly generate it. Even if you write alloc internally, Xcode will not warn you, but you cannot change the fact that it is destroyed once it is created.
          • The button created by the class method provided by Apple is received by weak but not destroyed. Why? Because the bottom layer of the apple framework is written in MRC, buttoWithType: The returned objects containautoreleaseIt means that the destruction will be delayed, but it will only be added to the automatic release pool, waiting for the scope of the automatic release pool or the automatic release pool to be destroyed. Instead of destroying them immediately. A classic interview question

            Q: Is there any problem with the following code? If so, how can this problem be solved?

            for (long i = 0; i < largeNumber; ++i) {        @autoreleasepool {            NSString *str = [NSString stringWithFormat:@"hello - %ld", i];            str = [str uppercaseString];            str = [str stringByAppendingString:@" - world"];        }    }

            Answer: If largeNumber is very large, too many automatically released objects will be created, and the automatic release pool may be "full". Tip: there is often one user interaction, far more than one, there will be a lot of code before and after the for, but this for will occupy a lot of space to automatically release the pool

            Solution

            The automatic release pool is introduced. There are two solutions on the network!

            1> automatically release the external pool (FAST): After the for loop ends, all automatically released objects generated internally will be destroyed after the for loop ends, will release the memory 2> Add the automatic release pool (slow): can be released every time the for generated automatic release object! Question: That method is highly efficient! Speed! Most tests are more internal than external ones! If you ask during the interview: I want to talk about it a little faster, "test it "!!! Tip: in daily work! Sometimes, the Code memory will soar! You need to know the solution!

            Set the value of largeNumner:

            long largeNumber = 5 * 1000 * 1000;

            Test Demo:

            NSLog (@ "Internal start"); CFAbsoluteTime start = CFAbsoluteTimeGetCurrent (); for (long I = 0; I <largeNumber; ++ I) {@ autoreleasepool {NSString * str = [NSString stringWithFormat: @ "hello-% ld", I]; str = [str uppercaseString]; str = [str stringByAppendingString: @ "-world"] ;}} NSLog (@ "end-% f", CFAbsoluteTimeGetCurrent ()-start); [self answer1];

            Answer1 method:

            NSLog (@ "start outside"); CFAbsoluteTime start = CFAbsoluteTimeGetCurrent (); @ autoreleasepool {for (long I = 0; I <largeNumber; ++ I) {NSString * str = [NSString stringWithFormat: @ "hello-% ld", I]; str = [str uppercaseString]; str = [str stringByAppendingString: @ "-world"] ;}} NSLog (@ "end-% f", CFAbsoluteTimeGetCurrent ()-start );

            Test results:

            11:18:50. 663 12-automatically release the pool of questions [28015: 743360] internal start2015-03-25 11:19:03. 996 12-questions about automatic release pool [28015: 743360] end-13.3323712015-03-25 11:19:03. 996 12-automatically release the pool of questions [28015: 743360] Outside start2015-03-25 11:19:18. 227 12-questions about automatic release pool [28015: 743360] end-14.230752

            It can be seen from the test results that for cycles, autorelease is added internally and externally. The speed is almost the same, and the internal speed is slightly faster, but it depends on the compiler. However, adding autorelease externally occupies a large amount of memory (note that, unlike not using autorelease, the memory opened without autorelease will not be released ). In development, it is usually added internally.

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.