Customizing XCode File Templates

Sunday, September 18, 2005

Want to customize/organize your XCode 2.1 templates??

Here's a few things I do to help myself.

First off let's get an understanding how this stuff works.

The location of file templates used for XCode are stored in /Library/Application Support/Apple/Developer Tools/File Templates/

You'll find several folders in the file templates folder. Notice that the names of the folders coincide with the names of the headings in the sheet that appears when you add a new file to your project.

Also, within each of those folders are folders with names that end in .pbfiletemplate. (The 'pb' is a left over from the previously used Project Builder application.) Within each .pbfiletemplate folder there is a class.h, class.m template file, and a TemplateInfo.plist. Just as an example open the /Library/Application Support/Apple/Developer Tools/File Templates/Cocoa/Objective-C class.pbfiletemplate folder. In that folder you'll find a class.m, class.h, and a TemplateInfo.plist file.

Open the TemplateInfo.plist file, which should automatically open in the Property List Editor application. In the Root node you'll find the Description of the template you see when you select this file template in the New File dialog. You'll also see the MainTemplateFile and its CounterpartTemplateFile which are set to class.m, and class.h respectively. Close the file without saving any changes you may have made.

Now open the class.m file. You'll see the template of the standard .m file. Within this file you'll see several elements using a particular pattern like the one for the file name ¬'FILENAME¬". These elements are replaced when you create an instance of the file in your project. Most of these elements are one's you probably don't want to mess with. However, one such element is listed as ¬'ORGANIZATIONNAME¬" which normally defaults to "__MyCompanyName__". This particular listing can be set up within the defaults of your XCode application. I'll explain that later, though.

So let's set up you own custom listing for files...

First Quit XCode and the Property List Editor applications, without saving any changes.

Now go to the /Library/Application Support/Apple/Developer Tools/File Templates/ in the Finder and create a new sub folder named "- My Classes". Now go to the Cocoa folder and copy the 'Objective-C class.pbfiletemplate' to the "- My Classes" folder. Now open XCode and create a new Cocoa Application project. Now add a new file to the project. Notice you'll see a heading of "- My Classes" with an "Objective-C class" listing. Just cancel for now, as we'll go ahead an make some further changes.

Rename the 'Objective-C class.pbfiletemplate' to 'NSObject subclass.pbfiletemplate'. Then open the TemplateInfo.plist with that folder.

Edit the Description listing under the Root element to say 'An Objective-C class file which subclasses NSObject, with an optional header which includes the header.'

And finally, edit the .m file to use /* and */ to hold the comments rather than the normal // for each line.

Now close and save both the .h file and the TemplateInfo.plist file.

Now attempt to add a new file to your XCode project. You'll see the "- My Classes" heading with the "NSObject subclass" listing. Select the listing and you'll see the new description show up. Now click next, give the file and name and click finish. Notice the new commenting style on the .m file's comments.

The quick and easy way to take care of that "__MyCompanyName__" information is to use the Terminal.

Enter the following line in the Terminal, replacing the Company Name with whatever you prefer.
defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{"ORGANIZATIONNAME" = "Company Name";}'

Chp 4 Challenge Solution

Friday, September 16, 2005

The challenge was to create a letter counting application.

So let's start out by launching Xcode, and creating a new project. Since the project is only one simple window, select a Cocoa Application as the project type and name the project "LetterCounter".

In the project, open the MainMenu.nib file.

Add two NSTextField controls, and one NSButton control to the window. Adjust the layout as shown in the book, or make up your own if you'd like. You will also want to remove any default text that is in your result field at this point, since it will be there when the application displays the window.

Once we've got things laid out, we need to add an object to handle the work of counting the letters and displaying the results.

To do this, go to the MainMenu.nib window containing your nib object instances. Click the Classes tab to view the classes currently available in your nib. Now, select the NSObject class in the first level of the hierarchy. (First column if viewing in standard column browser view, otherwise its the first level of the tree view.) Now, subclass NSObject into a new class named "AppController". Of course the name doesn't really matter, but AppController seems like the traditional name for this type of stuff.

Now that we have a class to act as the controller, we need to make it aware of the input field, and the result field we have in the window. With the AppController selected, go to the Classes menu and select "Add Outlet to AppController". You should see the inspector window showing the new outlet. Change the name of the outlet to 'inputTextField', and the type should be NSTextField. Next, add a second outlet with a type of NSTextField named 'resultTextField'.

In the inspector window select the outlet tab item and add a new action named 'countLetters'. Once you have the two outlet and one action defined. Go back the MainMenu.nib window, which is still displaying the classes tab item with AppController selected. Now we need to create an instance of this class, by selecting Instantiate App Controller from the classes menu.

When you instantiate the controller, it will appear in the Instances tab item.

Now we need to connect everything together. Control Drag from the AppController instance to input field on the application window and click connect in the inspector. Do the same for the result field. Now control drag from the button on the window to the AppController and connect the button to the countLetters: action.

Finally, we will add the necessary files for the AppController class to out project. Go to the classes tab and select the AppController class. Now go to the Classes menu and select Create Files for AppController. This should bring up a dialog to add the AppController.h and AppController.m to the LetterCounter target. Click the choose button to add the files.

Now save the nib file. We've done all we can here.

Now go back to Xcode and edit the AppController.m file. There should already be a countLetters: method ready to be completed. Edit the method like this...

- (IBAction)countLetters:(id)sender
{
NSString *entry = [inputTextField stringValue];

int letterCount = [entry length];

NSString *result =
[NSString stringWithFormat:@"%@ has %d letters."
,entry, letterCount]

[resultTextField setStringValue:result];
}


That should do it. Save the AppController.m file, build it and run it.

If things don't work, be sure to go and check your connections in the nib file, and double check the code for the method.

Happy Cocoa Travels!

Chp 3 Challenge Solution

Thursday, September 15, 2005

As promised I'm going to systematic answer each solution within the Cocoa Programming for Mac OS X.

The first part was just to add a format to the calendar date entry.

While the second just loops through the array to remove the items manually, and noticing that the item gets deallocated due to the retain count reaching 0.

Here's the adapted main method from the challenge at the end of chapter 3.

int main (int argc, const char * argv[]) {
NSMutableArray *array;
int i;

LotteryEntry *newEntry;
LotteryEntry *entryToPrint;

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSCalendarDate *now = [[NSCalendarDate alloc] init];
srandom(time(NULL));
array = [[NSMutableArray alloc] init];
for (i = 0 ; i < 10 ; i++ ) {
newEntry = [[LotteryEntry alloc] initWithEntryDate:
[now dateByAddingYears:0
months:0
days:(i*7)
hours:0
minutes:0
seconds:0]];

// Answer to part I of the challenge
// Tokens below are listed in Table 3.2 on pg 72
[newEntry setCalendarDateFormat:@"%b, %d %Y"];
[array addObject:newEntry];
[newEntry release];
}

for ( i = 0 ; i < 10 ; i++ ) {
entryToPrint = [array objectAtIndex:i];
NSLog(@"entry %d is %@", i , entryToPrint);
}

//This loop is the solution to the second part of the challenge
//Its removing each item one at a time
for ( i = 0 ; i < 10 ; i++ ) {
NSLog(@"removing item %d",i);
[array removeObjectAtIndex:0];
}

[array release];
[now release];
[pool release];
return 0;
}

Big Nerd Ranch

Wednesday, September 07, 2005

So, I've been doing some self-taught mac development using Objective-C and Cocoa for a few months and during those months I never gained enough knowledge to think I had anything to contribute to the mac development community. While I did have a few books on Cocoa programming I basically hunted around for the few things I needed to learn and never really absorbed the big picture.

The first step in gaining the big picture was the book "Cocoa(R) Programming for Mac(R) OS X (2nd Edition)" I went through this book in about 2 weeks and it put me on the road to developing something usable. I highly recommend it to anyone just starting out.

Now, while this book was indeed helpful, that still didn't motivate my mac programming esteem to the point that I would put anything out for public consumption.

The thing that put me over the edge was going to the Big Nerd Ranch's week long Cocoa Bootcamp instructed by one of the book's authors Aaron Hillegass.

Looking back at things I would estimate that this week long course would have cut about 4-6 months of self-discovery off my learning curve. If you want to hit the ground running with Cocoa development and you can swing the boot camp's admission price, I would suggest you do so.

The Big Nerd Ranch offers the class a few times a year, and now the class is even prefixed by a mini camp covering Objective-C. The language of choice for cocoa development. The Cocoa Bootcamp is held a the Historic Banning Mills lodge about 45 minutes outside of Atlanta, GA. The Big Nerd Ranch and the lodge take care of most everything for you. If you are flying in, the Big Nerd Ranch will pick you up at the airport and drive you to the lodge and return you to the airport when the class ends. Three meals a day are provided to you by the lodge. The meals are generously portioned and at no time did I every feel like I needed more than what was provided. Of course there were also small snacks available throughout the day as well. The private room included a jacuzzi tub, and wireless network service that allowed me to keep in touch with work and home. The only downsides were the need to hike up a small hill to reach a point that my cell phone would allow me to reach out, and I could have used a washing machine toward the end of my stay.

As far as the classroom instruction went, each section of learning would start with a small lecture. This would be followed by a little instructor lead hands-on exercise. Then the bulk of the time, would go to working from one of the chapters of the book which take you through a project that highlights one of basic building blocks of Cocoa development. Now, you might be thinking well damn, I could work from the book at home and save a bundle, and I would say more power to you. But, while I did learn quite a bit from the book, I remember times that I would get stuck and it would take me hours to figure out the typo I made, or the missed connection in interface builder. Nothing beats being able to raise your hand and have someone say, "Did you make sure to connect you button to the action" or "You forgot the * in your object reference."

In addition, each chapter of the book has challenges that extend your grasp of the subject beyond the standard excercise. These challeges have no published solutions, a situation I also intend to remedy in this blog, so classtime is wicked awesome for finding out how to acheive these challenges. Aaron also made himself available for a couple hours after dinner for an open lab. This lab time is great for the challenges, and to answer specific questions you may have for a project rumbling around in your head.

Welcome

Tuesday, September 06, 2005

Hi.

Welcome to the beginning of something I hope I can keep up with. I am relatively new to Mac development using Objective-C with the Cocoa framework and have decided that maintaining a bit of a public record of my growth will help accomplish two major goals.

First, for anyone who is traveling down a similar road will be able to learn from mistakes that I have made and possibly spend less time overcoming the same difficulties I have.

Second, for myself to learn faster and sharpen my skills as more experienced mac developers see my postings and provide criticism of anything I post. Believe me, I have a thick hide and will take anyone's input into account. So, if you feel the least bit compelled to spout off at me about anything I write, feel free to spout away. The only request I have is that if you tell me things like "Your code sucks", please do me the honor of telling me how it can be improved to suck less.

This page is powered by Blogger. Isn't yours?