Sam Stewart

Ramblings of a discombobulated programmer

0 notes &

When to call, how to use our friend: [super dealloc]

I’ve been refactoring an application for a client and continually ran into a peculiar error involving malloc. Apparently the code was trying to access an object which had already been released. I pored over each dealloc method until I narrowed the issue down by painful trial and error. The release statements appeared normal but I began to notice the [super dealloc] call was at the top of every dealloc method before the code released the other instance variables. Usually I place my [super dealloc] methods at the end of each dealloc, by convention, but I’ve never thought there was a good reason for doing so.

Until today. The crash which took me days to track down immediately disappeared when I moved the [super dealloc] call to the top of the dealloc method. The issue was sporadic and did not occur in every dealloc method which made it especially confusing. When you call [super dealloc] you are effectively destroying the heap space allocated for yourself thus invalidating all pointer references. If you then try to release the other instance variables, the system throws a cryptic error. This link on StackOverflow sums up the problem:

Filed under bugs objective-c iOS iphone programming beware

0 notes &

Don’t touch the UI in init methods

When overriding or adding an init method to a UIView or UIViewController do not touch any elements of the view hiearchay as this behavior can lead to unintended side effects. A common error is to do the following in an init method:

self.view.autoresizingMask = …;

This seemingly innocuous line of code will actually start the view loading and call loadView, viewDidLoad, etc. since self.view is really a getter. Of course, it is bad practice to load the entire view hierarchy from the init method; that should be done by the parent view when it’s ready to ensure “lazy loading”. The easy solution is to abstain from touching any UIView elements in the initializers; wait until viewDidLoad.

Filed under programming iOS tips coding uiview

1 note &

Using #pragma in Obejctive-C

When dealing with large files developers can add “#pragma mark …” statements to clarify  different sections. This is especially helpful when viewing the method listing in XCode.

To further demarcate the separations, “#pragma mark -” creates a horizontal line in the method listing. Up to this point I have thus been writing:

#pragma mark -
#pragma mark Calculation methods

Today I learned you can combine these two lines into:

#pragma mark - Calculation Methods

A small change, but it will eliminate one more unnecessary line of code!

Filed under tips reminder reference programming ios objective-c