Requirements before starting this tutorial:
You need an Intel based Mac (most of the new ones are Intel based, so if you got it with say OS X you should probably be fine here)
Internet connection
Downloading xCode:
First off, go to http://developer.app...ne/index.action and log into your Apple ID. This will allow you to see the more link required to download the iPhone SDK and xCode bundle.
Once you have logged in scroll to the bottom of the page (you should once again be at the index.action page). Select the appropriate download for your Mac and wait for it to finish (this can take a little while, it is about 2.3 GB file for the Snow Leopard download.
Installing xCode:
This is a very simple step. Click on the iPhone SDK desktop icon, then the iPhone SDK and Tools for <Snow Leopard/ Leopard> and follow the onscreen instructions.
Finding xCode, and the other Development tools on your Mac:
This step seems like it would be very simple, but it took me a little while to figure it out (never mind that I had only owned a Mac for about an hour at this point in the process…). Click on the documents icon in the system tray, then say “Open in Finder”, once the window opens click on “Macintosh HD” under “Devices”, if you followed the standard install paths and options there should be a folder here labeled “Developer”, click on that to open and then open the “Applications” folder under that to find the tools we will be using to develop iPhone applications.
For the basis of this tutorial we will be using xCode only and programmatically creating our user interface (UI), this is not to say it is the most correct way of doing things, but I just prefer having all my control objects stored in the same place instead of having everything scattered across multiple files and having to get them working together. The other option is to build your UI in Interface Builder and then only place the code for functionality needed in your Objective-C files.
For the moment just fire up xCode.
Creating a new project:
Now that you have xCode fired up on your machine select the “Create a new Xcode project” option from the welcome screen. This should pop up a list of premade templates. While it is fun to look through some of the more interesting ones just select iPhone OS -> Application -> Window-based Application. This will go through the required steps of creating the initial code for you.
If you want to see what the template has done for you click the “Build and Run” button at the top of the window, if it is not available you can also access it through Build -> Build and Run, or through Option + Enter.
As you can tell, this is a bare-bones project; but it won’t stay that way for long. We will now start the fun part – coding.
Merging files [optional]:
I find it best to merge all the working files into a single source file when learning a new language so I can mess with everything in one nice and simple place without having to know what part of a file goes where, or messing around with the requirements, so the first thing to do is get rid of “<project name>AppDelegate.h” and “<project name>AppDelegate.m”.
NOTE – Don’t just delete the files, they are still in the project, and are also responsible for doing everything that it currently does (showing the white window)!
Instead of deleting them, open each (starting with .h, then the .m) and copy its contents into “main.m”. Once you have copied the source code over select each of the two files and hit Delete (on the keyboard) then select “Delete References” and “Don’t Save”. The final “main.m” file should look like so:
#import <UIKit/UIKit.h>
@interface Hello_world_tutAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
@implementation Hello_world_tutAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
To make sure you copied it over correctly build and run the program again.
NOTE – If you haven’t closed the previous version running on the iPhone Simulator the compiler will give you some problems. To close it just press the home button at the bottom of the iPhone (it is not labeled, but is the button with the white square in it outside of the window we made).
Writing our own code [Adding a label]:
For the first part of this we will be adding a new variable to the <project name>AppDelegate interface. Now, for those of you C++ programmers it will be a pointer, but act as if it was a reference (dot notation instead of the arrow).
Add the following code to @interface <project name>AppDelegate : NSObject <UIApplicationDelegate>:
UILabel* myLabel;
Now, go to the function lower down called - (void)applicationDidFinishLaunching:(UIApplication *)application and add (to the end) this line of code:
myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 15, 310, 200)];
That is just saying “make myLabel a new UILabel, and bind it to a rectangle starting at x = 5, y = 15, and give it the width of 310 and height of 200”.
Now, you will of course want to put some text in it, so the easiest way to do so is with the following code:
myLabel.text = @“Hello World”;
And, to make it visible:
[window addSubview:myLabel];
So, the final code looks like so:
#import <UIKit/UIKit.h>
@interface Hello_world_tutAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UILabel* myLabel;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
@implementation Hello_world_tutAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 15, 310, 200)];
myLabel.text = @”Hello World”;
[window addSubview:myLabel];
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
Now, it is also important to make sure that you deallocate the memory used by each object upon ending the application. This is done with the release function, which you can call like so:
[myLabel release];
WARNING – Only use release when you are done with a variable. After you release a variable you will not be able to access it anymore and its memory will be returned to the system. However, the object will remain visible until you draw over it.
Adding some interactivity:
Now, it is time to add some interactivity. We have a nice little text box on our screen, so let’s add a button to change something about myLabel.
The first thing to do here is add the actual button. The easiest way to accomplish this is like so:
IBOutlet UISegmentedControl* myButton;
Now, remember to add that to your AppDelegate function so the whole class has access to it.
NOTICE – The button is using another identifier, IBOutlet, which is used (as far as my understanding goes – please inform me if I am wrong) for telling the application that this variable takes and dispatches events.
NOTE – UISegmentedControls can have multiple buttons attached to each other even though we aren’t doing that for this tutorial. If you wish you should be able to use UIButton with all the same properties.
Next, we need to initialize it, so place this code in your applicationDidFinishLaunching function:
myButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@”Button”]]; myButton.momentary = YES; myButton.center = CGPointMake(160, 400);
This makes the button with the label “Button” on it, then tells it that it should return to its normal state after being clicked (myButton.momentary = YES;), and then tells it to center itself at point (160, 400).
To make the button listen for an action add this function call:
[myButton addTarget:self action:@selector(ButtonPress) forControlEvents:UIControlEventValueChanged];
Which tells the button to pay attention to itself, when it is pressed call the ButtonPress function and also say that its value changed.
Writing ButtonPress:
If this is your first time looking at Objective-C functions will be very alien to you. That is okay, they are fairly simple to understand once you get the hang of them.
Starting off we will need to declare the function ButtonPress, which will return no value. In addition to not returning a value we want the function to be an instance function, and not a class function (I am still looking into the differences between the two…), this is accomplished by placing a “-“ in front of the function declaration.
- (void)ButtonPress is the first line of this function, but since we are going to be writing it inline just add to the end with a curly bracket and we will continue writing the function.
This function will be responsible for releasing the memory used by myLabel (to demonstrate the point I made earlier about how the object will remain drawn on the screen even after deletion). To accomplish this we will need to take a look at an if statement for comparison and then act based on the value the statement sees.
- (void)ButtonPress {
If (myLabel != nil)
{
[myLabel release];
myLabel = nil;
}
}
That tells the program to look at myLabel and see if its value is nil, if not it will release the memory and set myLabel = nil (so that it doesn’t try to release non-existent memory in the future).
Now, how do we know if the button is even calling ButtonPress upon multiple clicks? Well, luckily there is an easy (though a little annoying) way of checking.
Creating an Alert:
We will accomplish this little button click trial by alerting each and every time the button is clicked to make sure that the event is being heard. To do so you simply need to create an alert, show it, and release it, which is accomplished like so:
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@”Event” message:@”The button was pressed” delegate:self cancelButtonTitle:@”Okay” otherButtonTitles:nil]; [alert show]; [alert release];
Now, add that into your ButtonPress function (at the bottom) to see it in action. The final ButtonPress function is as so:
- (void)ButtonPress {
If (myLabel != nil)
{
[myLabel release];
myLabel = nil;
}
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@”Event” message:@”The button was pressed” delegate:self cancelButtonTitle:@”Okay” otherButtonTitles:nil];
[alert show];
[alert release];
}
Final Code:
The final code for this tutorial should look similar to this:
#import <UIKit/UIKit.h>
@interface Hello_world_tutAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UILabel* myLabel;
IBOutlet UISegmentedControl* myButton;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
@implementation Hello_world_tutAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
myLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 15, 310, 200)];
myLabel.text = @"Hello World";
[myLabel setAlpha:0.5];
[window addSubview:myLabel];
myButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Click to release myLabel"]];
myButton.momentary = YES;
myButton.center = CGPointMake(160,400);
[myButton addTarget:self action:@selector(ButtonPress) forControlEvents:UIControlEventValueChanged];
[window addSubview:myButton];
}
- (void)ButtonPress {
if (myLabel != nil) {
[myLabel release];
myLabel = nil;
}
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Event" message:@"The button was pressed." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)dealloc {
[myButton release];
if(myLabel != nil){
[myLabel release];
}
[window release];
[super dealloc];
}
@end
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
Well, hopefully you learned something from this tutorial, check back soon for the next installment.








MultiQuote








|