Thursday, April 18, 2013

How to track allocations and deallocations when using ARC

If you are new to ARC(Automatic Reference counting), you might feel that you have lost control of the allocations and deallocations of objects. Well, the truth is, that's why ARC was invented. So you don't need to track the allocations and deallocations. But sometimes for debugging purposes it might help to know when a particular object is being allocated and deallocated. A very simple method for this is to add the following lines of code to the class whose object you want to track. The example below is for a view controller class



You will observe that as you run your app, the init and dealloc log messages will be displayed in the xcode console as and when your object gets allocated and deallocated.

If you happened to get some error messages saying that an initWithCoder function could not be found, then just override the init function instead of initWithCoder. Classes derived from NSObject would not have an initWithCoder function unless it implements the NSCoding protocol.

You shouldn't have to track allocations and deallocations regularly if you are using ARC because ARC does a pretty good job of handling it. But in the rare occasion when you feel something is not going as planned, it doesn't hurt to double check.

Did you find this helpful? Do you have a special way of tracking memory? Do let me know.

No comments:

Post a Comment