Friday, 29 June 2012

Automatic Reference Counting (ARC)

Automatic Reference Counting, otherwise known as ARC, is a feature implemented in Xcode 4.2+. In previous version programmers had to maintain memory management manually, ensuring they dismissed objects after they were finished using them.

As anyone with programming experience knowns this can be tiresome as miss an object and you can get memory management issues which can lead to no end of trouble. ARC handles all this for you.

When using ARC, enabled by default in any Xcode 4.2+ projects, as long as your implement the right code in your functions the complier will work out, and add the relevant code, for when objects should be dismissed.

ARC is incredibly easy to implement. If you have a function as follows:


//
//  NumGenViewController.m
//  NumGen
//
//  Created by James Krawczyk on 29/06/2012.
//  Copyright (c) 2012 James Krawczyk. All rights reserved.
//

- (IBAction)GenNum:(id)sender 

{
    int ran = 0;
    ran = arc4random() % 1000;
    numOut.text = [NSString stringWithFormat:@"Num: %i", ran];
}


All you have to do to implement ARC is add @autoreleasepool { and then a corresponding closing } at the end of the function, as so: 

//

//  NumGenViewController.m

//  NumGen

//

//  Created by James Krawczyk on 29/06/2012.

//  Copyright (c) 2012 James Krawczyk. All rights reserved.

//


- (IBAction)GenNum:(id)sender 



{

    @autoreleasepool 

    {

        int ran = 0;

        ran = arc4random() % 1000;
        numOut.text = [NSString stringWithFormat:@"Num: %i", ran];
    }
}

In order to use ARC effectively you need to add this to every function you create that will be using objects.

No comments:

Post a Comment