JLA: January 2008 Archives

No Garbage Collection
    If you are coming from Java, you are probably used to creating variables and having someone else clean up your mess after you are finished with them.  Unfortunately, on the iPhone, you have to clean up after yourself.   If you don't, your program will leak memory. 
    It isn't exactly manual labor, however.  The NSObject class has some accounting stuff that keeps track of how many other objects are currently using the object in question ("retain count").  But unlike Java, it isn't automatic...you will have to adjust this count yourself.
    The analogy that is frequently used is that of a time-share condo...a condominium with multiple owners.  And this condo sits on valuable land.  As soon as the all the owners are done using the condo, it can be bulldozed to make way for other buildings.  The "retain count" of the condo would be the number of owners (i.e. those who are still wanting to use it). 

Adjusting the Retain Count  
    The rule of managing memory is to make sure that, by the time the program has finished executing, the number of "ownership methods" called on an object will equal the number of "loss-of-ownership" methods.

Ownership methods:
Don't release anything you don't own. You own anything that (any of the following):
  1. you call [myClass alloc] explicitly on
  2. you explicitly [myObject retain]
  3. you create an object with a method that has the word "copy" in it.
Note: you do not own objects created by convenience constructors...they are set to autorelease.  (An example of calling a convenience constructor: [NSString string];)

Loss-of-ownership methods:
To release something you own, you can either:
  1. call [myObject autorelease] - will release later
  2. call [myObject release]

Dealloc
Never directly call dealloc...you should always use release, and let the system decide when to deallocate.

You should override dealloc for each of your objects, and inside that method, release anything you have retained. And the end of the method, call [super dealloc]; (It's okay to call release on a null object).

Bookkeeping
When you implement a "set" method for encapsulation, you should do the following:

- (void) setSomeObject: (NSObject*) aNewObject
{
[aNewObject retain]; //#1
[myObject release]; //#2
myObject=aNewObject; //#3
}

#3 obviously sets the new object
#2 is called just in case you have a previous object...you should release it before you set it free. It is perfectly okay to call release on a null object.
#1 - always retain the new one first, just in case they are passing the same object in that is already assigned. Otherwise, you may end up deallocating the object.

And if you release a variable somewhere other than dealloc, you might want to set that variable to nil immediately afterwards.

Autorelease
    Suppose you add a convenience constructor to your own object.  Or you have a method that allocates and returns an object that you don't plan on "owning".  If you call "alloc", you will have to balance that out with a release of some sort.  But you can't call "release" before you return it--the object will cease to exist.  So instead, you call "autorelease".  This will cause it to be released at some point in the near future, but not immediately.

Example:

+ (id) createAnObjectForMe
{
return [[[MyClass alloc] init] autorelease];
}
  
Here is the settings menu from Garf.  Each row has a height of 48.0.  There are 3 groups and a total of 8 rows.  Groups 0 and 1 each have two rows, while Group 2 has one row.


GarfSettingsA.JPG







The arrow head (pointy-bracket) is achieved by calling "setShowDisclosure:YES" on the preference cell.

Most of the cells are of the type:
UIPreferencesTableCell






The "High scores" cell is of the following type: UIPreferencesControlTableCell.

The switch inside of it is of the type:
UISwitchControl






GarfSettingsB.jpg

Source Code and Packages

| | Comments (0) | TrackBacks (0)
Source Code
    When you start programming your first original program, you'll probably want to reuse the "main.m" source file that you find in another program (e.g. HelloWorld).   Just edit it and make sure it is importing your program's header.  And of course make sure it is specifying your program's name in the call to UIApplicationMain.  This should be self explanatory when you actually see it.
    So let's say you are creating a program called "Big Gulp".  Here is the layout of files I recommend:
  • main.m (a very small file...)
  • BigGulp.m (your primary application class...of type UIApplication)
  • BigGulp.h (the header file for your application class)
  • Makefile (the make file...recycle this from another program...be sure to edit it to make sure the filenames match your program)
Building Your Program
    When you want to compile and link your program, you will want to use a Makefile.  I'm no expert on this subject, and how they work is still somewhat of a mystery to me, but I do know that you it's best to copy the Makefile from another iPhone program you find and edit it to make sure it fits your program.  Be very careful...the file is very picky about white space (tabs, etc).  The Makefile easily deserves its own article, and so I won't go into too much detail here, but for now, you should be able to look at one and see what needs replacing.
    To compile, go to the prompt in your program's directory (e.g. Cygwin for Windows users).  If the Makefile is set up properly, the command "make clean" should delete any previously compiled binaries and give you a fresh plate...so go ahead and type that.  Then follow that by typing "make".  If it builds correctly, it should produce an executable file (whose name you specified in the Makefile).  Unlike Windows executables, this file will not have a special extension (.exe).  Or any extension, for that matter.  It will simply be plain extensionless file.

Package structure
    When you want get your program ready for installing on the iPhone springboard, you should create a directory on your computer called BigGulp.app (replacing "BigGulp" with the name of your app). 
    This folder should eventually contain the following files:
  • biggulp (or whatever your executable is called)
  • icon.png (the icon for your program)
  • Default.png (the splash screen for your program...should be 320 x 460)
  • PkgInfo (get this from another program and don't change it)
  • Info.plist (get this from another program but DO change it...)
  • (any other graphics file, etc. that your app needs)
Info.plist
    This is another file that you should borrow from some other iPhone program.  You will need to edit however.
    Specifically, you should edit the strings that come after the following labels (keys):
  • CFBundleExecutable - this should specify your app's executable file (e.g. biggulp)
  • CFBundleIdentifier - this should be some unique string...one that no other app in the world will have.  You may notice that it frequently looks like a web address in reverse.  This is merely a convention of coming up a unique identifier...since only one entity (company) will "own" a website name, two different companies won't accidentally use the same identifier.  Note that there is no requirement that this name have anything to do with a website, or that a website exists.  One place this identifier will be used is when you save user defaults, the iPhone will create a file by that name in the Preferences directory.
  • CFBundleVersion - this is whatever arbitrary version you have assigned to your app.
You should leave the other stuff alone, including the CFBundleInfoDictionaryVersion. 


Installing the app
    To install the app on your iPhone, you will simply need to copy the .app directory you just made into the /Applications directory on your phone (via SSH).  Make sure that both your app's directory (e.g. BigGulp.app) and the executable file inside it have full Execution permissions.  This is done by either your SSH program or by using an app like MobileFinder.
    After doing this, you will need to "respring" the phone...that is, restart SpringBoard.  There are a couple of apps that can do this for you, including SysInfo (from Robota Software - available on Installer).  Or you can simply reboot your phone (so it starts up again, showing the silver apple).  Your app should show up on the springboard.



Getting started (on Windows)

| | Comments (0) | TrackBacks (0)
Windows user?
    If you use Windows, you are at a slight disadvantage when it comes to developing for the iPhone.  Mac users have the (alleged) benefit of XCode.  Windows users, however, must make it on their own. 

Toolchain
    Obviously, the first step is to get the toolchain up and running with Cygwin.  Cygwin is a Linux shell (i.e. command prompt) emulator for Windows.  It is distributed with a setup file that makes it very easy to download most of the components you'll need (sort of like Installer on the iPhone).   To get everything setup, see the first entry of this blog.

Text editor
    You'll need a good text editor that is Unix friendly.  Windows (DOS) uses a different combination of invisible keys to mark the end of each line than Unix.  For this reason, I wouldn't recommend any Microsoft products. 
    The text editor I use is jEdit.  It's a free download and has a good number of easy-to-install plugins.  Fairly programmer friendly.

HelloWorld
    Once you have the toolchain up, you'll need to find a copy of the UIKit version of HelloWorld.  HelloWorld, in case you are new to programming, is the traditional name for the first program  you compile.  It's a fairly worthless program, but it serves to a) test the toolchain and b) provide a template for your future programs.
A brief Java-oriented glossary
If you are coming from Java (the language, not the place), then here's a very brief Java-to-UIKit guide.  (Note: some of these are only approximately equal)
  • interface (Java) = protocol (ObjC)
  • static method = class method
  • java.lang.Object = NSObject
  • javax.swing.JOptionsPane = UIAlertSheet
  • null = nil
  • System.out.println("my object=" + myObject); = NSLog(@"my object=%@", myObject);
  • "a literal string" = @"a literal string"
  • java.lang.String = NSString
  • boolean = BOOL
  • java.util.ArrayList = NSMutableArray
  • map = dictionary
  • this = self

For loop
One thing that sort of bugs me is that you aren't allowed to do this: "for (int i=0; i<10; i++)"...you can't declare the variable 'i' there.  You have to do this instead:
int i;
for (i=0; i<10; i++)


Methods in ObjC
(Note: the word "method" will be used interchangeably with the words "function" and "procedure".)

The most obvious difference between Java and Objective C is probably the ways methods are declared. 

A regular ole method declaration looks like this:
- (int) getSomeNumber: (int) aParameter withAnotherParameter: (NSString*) aStringParameter
This would be equivalent to:
private int getSomeNumber(int aParameter, String aStringParameter)

  • First, notice that it starts with a hypen (a minus sign).  If this were a plus sign (+), it would mean the function is a "class method" (known in Java as a static method).
  • Next, notice that Objective C puts the variable type in parentheses, sort of like you do when you cast from one type to another.  The parentheses do not enclose the entire parameter list.
  • Notice there are no commas...also note that ObjC uses labels for parameters (starting with the second one).  In the previous example, it is "withAnotherParameter".  This is just something that helps describe what the next variable is, and I could have just as easily used "fooMcLovin" or some other nonsense instead.
  • The asterisk means that ObjC uses the same pointer notation as C/C++.

When you call the function, it will look something like this:
int x = [myObject getSomeNumber: 32 withAnotherParameter: @"some string I made up"];
(Technically, in ObjC, you aren't calling methods...you are sending messages, but we'll ignore this distinction for the time being.)


Other differences
There are many more differences that I'm not going to cover in this article...e.g. header files, pointers, memory management (no more garbage collection).  These will hopefully be addressed in some form or another in later articles.
Purpose of this blog
    As of the time of composition of this initial entry, the iPhone Software Development Kit (SDK) is set to be released in a little over a month.  This will allegedly allow 3rd parties to develop native software for the iPhone.  I say allegedly because Apple is releasing this with some reluctance...I'm not sure exactly who this SDK will target, but my guess is that it will be aimed at professional developers who work for "significant" software companies.
    This blog isn't intended for professional programmers, but rather the amateur...the hobbyist developer who wants to write something for the iPhone.  I feel I am especially qualified for this because I am only one step up from the "noob"...my profession has very little to do with computers, and I can certainly relate to how confusing this all can be. 
    If you fit into this hobbyist demographic, you will want to have a jailbroken iphone.  To "jailbreak" an iPhone is to uncripple it so that it will allow 3rd party native applications...(don't confuse "jailbreak" with "unlock" the the media often does).  If you haven't reached this step, I recommend visiting a site like ModMyIfone.com, which will have plenty of information on how to do this.
    It should go without saying that this blog has absolutely no affiliation with Apple. 
   
Native Apps versus "Web Apps"
    A native application is one that runs...well...like a real application.  It resides on the iPhone storage drive, and it runs without requiring a web browser.   A "web app" (notice how I belittle it with quotation marks) is (in my opinion) a fancy web page.  This blog will deal with native apps.

What is required?
So you want to develop software for the iPhone...what will be required?
Here are the requirements that involve spending money:
  • An iPhone or an iPod Touch
  • A home computer (Windows, Mac, whatever)
  • An Internet connection
  • A wireless router (for transferring your app to your iPhone to test it)
The rest of the stuff needed can be downloaded for free.

Programming experience
While programming experience for non-iPhone stuff isn't absolutely required, you probably want some under your belt before attempting to program for the iPhone.  If you have programmed for the Mac before, this will be a breeze for you to learn.  If you are a C++ person, this will also be fairly easy.  I am personally coming from the land of Java.  If you have never programmed before, I definitely recommend you spend a few months (at least) toying with Java.  Why?
  • Java is very friendly for those who are new to programming
  • Java is popular on a variety of computer operating systems, including yours
  • There is a whole lot of help available on the Internet for Java programmers.
  • There are tons of "Beginner's Guide to Java" type books in bookstores
  • Java has really great (and free) IDEs like Netbeans and Eclipse.
Note that none of the above really apply to iPhone development.  And also note that the stuff above and below represents my personal opinion.

Programming languages in iPhone development
    So what programming language is used to make iPhone apps?  The simple answer: Objective C (ObjC).  Outside of the land of Apple, ObjC is fairly obscure.  So what is Objective C?  Let's go back to C. 
    C is the foundation for a number of languages.  It isn't as often used by itself anymore because it isn't object oriented...it doesn't use classes/objects.  So a number of languages added object-oriented capabilities onto C.  One of these was C++.  Another of these was ObjC. 
     So because ObjC was built on top of C, C can be freely used throughout an Objective C program.  So you could program an iPhone app in C, with only a dab of ObjC in the whole thing.  But you'll find that ObjC isn't difficult to learn.

UIKit?
    So you may have heard about UIKit...what is that?  Specifically, it's a single framework (i.e. set of classes) that contains classes needed for iPhone user-interface (UI).  (Sort-of like what Swing is for Java.) 
    UIKit is often used, however, in a more general sense to mean not only the UIKit framework, but all of the frameworks present on the iPhone.  And it's sometimes used to refer to the entire iPhone programming experience.

So what's the next step?
So before you get going, you'll need what is called the toolchain.  This is a 3rd party bundle of software that is used to build programs for the jailbroken iPhone.  You can either find a precompiled binary for your computer system, or you can build it yourself.  If you do choose the old-fashioned build-it-yourself technique, check out the toolchain site for instructions.  If you use Windows, however, I recommend you using a separate set of instructions that are tailored to Windows.  There may be a copy of these on the wiki portion of the ModMyIfone site, but you may have to look around to find them.
  

About this Archive

This page is a archive of recent entries written by JLA in January 2008.

JLA: February 2008 is the next archive.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Powered by Movable Type 4.1-en-release-26-r1120-20071224