Generating Objective-C Code With Ruby: Part 2 — Dealloc December 16, 2009 at 8:28 pm
Something that I often forget until days into working with a new controller is the dealloc method. There are a lot of steps involved in setting up a IBOutlet or property. I typical notice all at once and need to add releases for somewhere between 3 and 12 objects. This is a great time to use Ruby to save some typing.
Now there is some debate out there in the Cocoa world about whether or not you need to release objects pointed to from IBOutlets when you use a NIB to initialize. On the iPhone, if you are using an @property(retain), the answer is: “YES, YOU NEED TO RELEASE!!!”. Setting the pointer to nil also makes sense in many situations, but is not needed in the dealloc. The pointer is going to be gone very shortly anyway.
Now, this is a problem that is trivial to solve with Ruby. I want to give a script the declarations from my header file and have it give me back the code I need in my dealloc method. Of course I only want to release objects, so i skip any lines that don’t contain a “*”. If you are using a lot of untyped pointer (id), you may want to add support for that. Thanks to Joe Pecoraro for helping me make this code more rubytastic.
puts
File.open(ARGV[0]).each do |line|
line = line.split
if line[0] == "IBOutlet"
puts "[#{line[2].tr('*;','')} release];"
elsif line[1] and line[1].include? "*"
puts "[#{line[1].tr('*;','')} release];"
end
end
puts
We put the input data into a file and pass that file name as the first arg to our script. Sample data could be
NSArray *gorillas;
IBOutlet UISearchBar *searchBar;
IBOutlet UISegmentedControl *seg;
IBOutlet UITableView *tView;
BOOL firstAppear;
NSSoupPot *pot;
and we get back
[titles release];
[gorillas release];
[searchBar release];
[seg release];
[tView release];
[pot release];
I know that’s not that much text, but the key here is having a shell open and ready to go at all times. Then this can be a time saver.
