Check Your “self” Before You Wriggity Wreck Yourself

I had an annoying day of trying to track down memory leaks and other memory-related iPhone development problems yesterday which turned out to be caused by a really simple and careless absence of the word “self” in one of my initialization methods. Observe.

itemId = itemIdentifier;

is definitely not the same as

self.itemId = itemIdentifier;

This is nothing new or earth-shattering. It just can cause you a lot of pain if you aren’t careful about it. The first one is a direct variable assignment. The second is a syntactically nicer way of sending this message:
[self setItemId:itemIdentifier];

Here is the implementation of the really bad initWithItemId:name method that was causing all my pain:

- (id)initWithItemId:(NSString *)itemIdentifier name:(NSString *)nameOfItem {
  if (self = [super init]) {
        itemId = itemIdentifier;
        itemName = nameOfItem;
    return self;

Because I didn’t use the dot syntax, the setter methods for itemId and itemName properties were never getting called, and the ref counts for their variables were not getting incremented. This resulted in them becoming pointers to invalid memory as soon as the itemIdentifier and nameOfItem variables went out of scope and were released by the code that owned them…and that resulted in bizarre functionality and crashes that caused me to grind my teeth, pull my hair, and get angry at myself for taking so long to track them down. No one likes an angry Sam. From now on I will be double-chiggity checking my self.

This entry was posted in Software Development and tagged , , .
Bookmark the permalink.
Follow any comments here with the RSS feed for this post.
Both comments and trackbacks are currently closed.

librarian, writer/editor, floundering guitarist, breakfast addict

mobile software developer, dog owner, hiker, adventure racer, enemy of bureaucracy
Follow sam2themax on Twitter Subscribe to this blog