Automatically generating Objective-C .h files from .m files
Last weekend I participated in Hack Nashville and built a social pixel-art app called 46px. It was a fun project, but our team of four programmers hacking things together over the course of two days made quite a mess. We rushed to finish the app and one of the first things to go was .h/.m file consistency.
Now I need to update most of the project’s .h files to remove warnings. In the past, this has amounted to:
- Copying the functions, body and all, from the .m file to the .h file.
- Removing everything in the brackets, adding a semicolon.
- Repeat for hundreds of functions.
That workflow pretty much sucks. It’s not what I want to spend my day doing. I set about to do it a better way and discovered that it isn’t too hard to automate this mess with Automator and BBEdit’s GREP functionality.
Cut to the chase, download the Workflow:
Copy Function Headers.workflow
Here’s the breakdown of Grep functions to perform the above:
// remove all of the lines that are not pragma marks or method declarations
1. Find: ^(?!#pragma)((?!([-+]+[^;{]*)\r).)*$\r
Replace With: <nothing>
// Add a semicolon to the end of each method declaration
2. Find: ^([-+]+[^;{\-\+]*)\r
Replace With: \1;\r
// Remove any stray close brackets
3. Find: }
Replace With: <nothing>
// Identify pragma marks and add a leading and trailing carriage return
4. Find: (#pragma.*)
Replace With: \r\1\r
// Find places where two or more lines of pragma marks in a row caused a series of three carriage returns in a row.
5. Find: \r\r\r
Replace With: \r
I realize this is a hackāhell, that series of grep commands does and then _undoes_ some carriage returns. But at the end of the day, it works pretty well, and you get something like this:
#pragma mark - #pragma mark UITableView Data Source Functions - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath; - (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath; #pragma mark - #pragma mark IBActions - (IBAction)helpIconTapped:(id)sender; - (IBAction)questionCountSliderChanged:(NumberRangeView*)slider; - (IBAction)operandRangeSliderChanged:(NumberRangeView*)slider; - (IBAction)timerSliderChanged:(NumberRangeView*)slider;
To use this Automator Workflow, double click to install it and then go to System Preferences > Keyboard and add a Keyboard Shortcut to Xcode. Tie a hotkey of your choice to the menu item “Copy Function Headers”.
The new workflow?
- Select the body of a .m file.
- Press the hotkey you assigned the action to.
- Paste into .h file.
Enjoy! I hope this saves you as much time as it’s saved me.


No Comments, Comment or Ping
Reply to 'Automatically generating Objective-C .h files from .m files'