• (2 Pages)
  • +
  • 1
  • 2

iPhone Development Tutorial - Part 1 [Introduction to Obj-C, xCode, and iPhone SDK] Rate Topic: ***-- 2 Votes

#1 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1148
  • View blog
  • Posts: 7,154
  • Joined: 07-September 06

Post icon  Posted 30 November 2009 - 02:22 PM

*
POPULAR

iPhone App development part 1 [Introduction to xCode and Objective-C]

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.

Is This A Good Question/Topic? 8
  • +

Replies To: iPhone Development Tutorial - Part 1

#2 skyhawk133  Icon User is offline

  • Head DIC Head
  • member icon

Reputation: 1875
  • View blog
  • Posts: 20,284
  • Joined: 17-March 01

Posted 30 November 2009 - 02:51 PM

Submitted to DZone... Vote for it here: http://www.dzone.com...ial_part_1.html
Was This Post Helpful? 0
  • +
  • -

#3 markhazlett9  Icon User is offline

  • Coding is a lifestyle
  • member icon

Reputation: 60
  • View blog
  • Posts: 1,666
  • Joined: 12-July 08

Posted 30 November 2009 - 05:30 PM

Finally an iphone tutorial! Thanks BetaWar!
Was This Post Helpful? 0
  • +
  • -

#4 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1148
  • View blog
  • Posts: 7,154
  • Joined: 07-September 06

Posted 30 November 2009 - 07:56 PM

No worries :)
I finally bit the bullet and bought a Mac, so I can actually start developing for the iPhone.
Was This Post Helpful? 0
  • +
  • -

#5 calebjonasson  Icon User is offline

  • $bert = new DragonUnicorn(); $bert->rawr();
  • member icon

Reputation: 209
  • View blog
  • Posts: 989
  • Joined: 28-February 09

Posted 01 December 2009 - 01:57 AM

Very nice work.
Was This Post Helpful? 0
  • +
  • -

#6 didgy58  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 246
  • Joined: 23-October 07

Posted 01 December 2009 - 03:54 AM

are you going to be doing more? perhaps a series of iphone development?
Was This Post Helpful? 1
  • +
  • -

#7 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1148
  • View blog
  • Posts: 7,154
  • Joined: 07-September 06

Posted 01 December 2009 - 09:10 AM

Yes, the plan is to write a series, starting at the basics then going more in depth.
Was This Post Helpful? 1
  • +
  • -

#8 didgy58  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 246
  • Joined: 23-October 07

Posted 02 December 2009 - 04:24 AM

great thanks betawar, this is something that i would like to get into.
Was This Post Helpful? 0
  • +
  • -

#9 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3102
  • View blog
  • Posts: 19,142
  • Joined: 14-September 07

Posted 02 December 2009 - 06:25 PM

Voted up, this is nice :^:
Was This Post Helpful? 0
  • +
  • -

#10 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Posted 02 December 2009 - 07:05 PM

Also on Digg! Digg it please! :^:
Was This Post Helpful? 0
  • +
  • -

#11 felixtgomezjr  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 68
  • Joined: 04-November 09

Posted 29 January 2010 - 11:13 PM

great job man! I have been struggling on how to code for iphone apps but most of the tutorials uses IB and I just cant get it. Maybe because I am used to do hard code. Now with this tutorial, I can say that I understand 75% now on how to code for iPhone.

I have a question though. Is it 100% possible to get rid of IB? I just want to code in the way you code.

Please enlighten me on this matter.
Was This Post Helpful? 0
  • +
  • -

#12 williamgeorgegardner  Icon User is offline

  • CEO of GeekTelligence
  • member icon

Reputation: 19
  • View blog
  • Posts: 584
  • Joined: 27-December 09

Posted 19 February 2010 - 08:31 AM

What Mac did you get and what resources did you use to learn Objective-C?


Great tutorial!!!!
Was This Post Helpful? 0
  • +
  • -

#13 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1148
  • View blog
  • Posts: 7,154
  • Joined: 07-September 06

Posted 19 February 2010 - 08:39 AM

I am using the standard model mac book (not pro), with x-Code. I used Apple's tutorials, google, and x-Code's auto-complete to learn.
Was This Post Helpful? 0
  • +
  • -

#14 shalinda  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 16-December 08

Posted 27 April 2010 - 05:07 AM

Great work BetaWar. The method that you use to explain is very simple and clear. I went through many documents but most of them are boring and too much complex. After reading your article I felt that I can develop iPhone applications. Looking for more article.(Just do a series of article I hope it would be make a hit!!!). Good Luck!!
Was This Post Helpful? 0
  • +
  • -

#15 erburrell  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 10
  • View blog
  • Posts: 145
  • Joined: 22-December 09

Posted 10 November 2010 - 11:26 AM

Great tutorial!

While I am sure you have figured out the answer to the statement below:

Quote

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.


for the assitance of others who are still wondering, please see the following link.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2