Search Your Question

What is AutoReleasePool?

Ans : 

In simple word, it is pool contained objects that will be released in some time.

Object's retain and release is constant action on object. For that Retain() and Release() methods called in objective c to control memory flow. As iOS objects work on retain count concept, it tells retain counts and it will be released if it reaches to 0.

Sometimes, we can not continuously use Release() method to release object.

Code for example :

 -(NSString *)getCoolLabel {
    NSString *label = [[NSString alloc] initWithString:@"SwiftRocks"];
    [label release];
    return label;
 }

    

Here label has 2 retain count and after return it has 1 retain count. It will be in memory as we can not execute release after return label; statement.

So solution :
return [label autorelease];
It will not release label instantly, but it inserts label in pool, and in some time, when autorelease pool thread execute, it

Note : Instead of instantly reducing the retain count of an object, autorelease() adds the object to a pool of objects that need to be released sometime in the future, but not now. By default, the pool will release these objects at the end of the run loop of the thread being executed, which is more than enough time to cover all usages of getCoolLabel() without causing memory leaks.

Whatever code that takes much memory we can add in autoreleasepool block.
I.e

@autoreleasepool {
           NSString *contents = [self getFileContents:files[i]];
           NSString *emojified = [contents emojified];
           [self writeContents:contents toFile:files[i]];

       }

Above all code written in objective - c, but in swift AutoReleasePool is required?

Yes, it depends on code.  It’s a different story if your code is dealing with legacy Obj-C code, specially old Foundation classes in iOS.

To put it short, autoreleasepool is still useful in iOS/Swift development as there are still legacy Obj-C classes in UIKit and Foundation that call autorelease, but we not have to worry where there is pure swift code.



No comments:

Post a Comment

Thanks