RSS
 

Generating Objective-C Code With Ruby: Part 2 — Dealloc

16 Dec

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.

#!/usr/bin/ruby

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 *titles;
NSArray *gorillas;
IBOutlet UISearchBar *searchBar;
IBOutlet UISegmentedControl *seg;
IBOutlet UITableView *tView;
BOOL firstAppear;
NSSoupPot *pot;

and we get back

jcannatti@li103-64:~/code/scripts/ruby_scripts$ ./dealloc_generate.rb data

[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.

 
1 Comment

Posted in General

 

Leave a Reply

 
 
  1. Joseph Pecoraro

    December 21, 2009 at 2:57 am

    After working with JavaScript for so long its nice to see some Ruby. I’ve missed it. I’ll throw some tips out there. There are easier ways to read lines from a file. The easiest is just using “each” on the file object itself.

    File.open(ARGV[0]).each { |line| … }

    That little trick will manage to cut out a few boiler plate lines from the Ruby script. Minor style nits would be that “puts” doesn’t need the empty string and ()s are optional on methods. Produced the following:
    http://gist.github.com/260844

    I’ll be watching for more scripts. Cheers.