/ / INTRODUCTION
The iPhone is a small computer with a multi-touch screen, a microphone for audio input, and an accelerometer to measure g-forces that can be translated to tilt, if desired.
What do you need to program the iPhone?
SDK and Xcode, Interface Builder and Instruments.Xcode is an Integrated Development Environment (IDE) that takes care of file management, compilation, debug- ging and error reporting. You’ll use Xcode to manage your project and to write, run, and debug your code. You’ll use Interface Builder to create your interface and to wire it to your code. Instruments will help you identify areas that are hurting your performance.
Objective-C
Objective-C is a language similar to ANSI C or C++ but with a much more robust set of instructions, classes, and shortcuts.Objective-C extends the standard ANSI C language by providing syntax for defining classes, methods, and properties, as well as other constructs that promote dynamic extension of classes. The class syntax and design are based mostly on Smalltalk, one of the first object-oriented programming languages.
As with C code, you define header files and source files to separate public declarations from the implementation details of your code.
/ / FRAMEWORKS
The iPhone Software Architecture
The iPhone’s software stack is divided into a number of layers, with your application at the highest level of abstraction and core system services at the lowest level. From highest to lowest-level, the stack can be summarized as follows:- Your application
- Cocoa Touch — Framework for developing touchscreen applications:
UI elements, event dispatching, application life-cycle, etc.
Also includes object wrappers around essential data types (strings,
collections).
- Media — Graphics, animation, sound, video.
- Core Services — Collections, strings, location awareness, SQLite
database, address book, networking, etc.
- Core OS Layer — UNIX services, standard I/O, threads, BSD sock-
ets, power management, etc.
You’ll mostly want to work primarily with the GUI frameworks and the OO abstractions offered by the Cocoa Touch layer. Most of the Cocoa Touch classes are designed to be called directly from your code; you can subclass these classes to add additional functionality, but you’ll find that you need to do this far less frequently than in other languages.
So what's a framework?
A framework is a set of classes and routines that have been grouped together to make developing programs easier. It is a collection of parts that caninclude:- header files
- libraries
- images
- sounds
There are more than 8 frameworks available for developing applications in Mac OSX. The framework that provides the base or foundation for all your program development is called the Foundation framework. This framework enables you to work with basic objects—numbers, strings and collections of objects.
The Application Kit framework contains an extensive collection of classes and methods to develop interactive graphical applications. These provide the capability to easily work with text, menus, toolbars, tables, documents, the pasteboard, and windows. In Mac OSX, the term CocoaFoundation and Application Kit frameworks. Cocoa Touch refers to the Foundation and UIKit frameworks.
Each framework has a master header file that includes all the frameworks individual header files. By using #import on the master header file, you have access to all the framework's features.
Cocoa Touch
The Cocoa Touch application frameworks contains most of the classes you will use to develop your first applications. The term comes from Cocoa, the object-oriented frameworks developed for Mac OS X programming (and NextStep before that), along with GUI classes uniquely designed for use on a mobile, touchscreen device (hence the Touch).Cocoa’s Foundation framework includes essential data classes, basic utilities, and establishes some core programming conventions that can- not be expressed by the Objective-C language alone, such as techniques for managing memory. All Cocoa classes inherit from a root class, NSObject, defined in Foundation.
Cocoa also provides a set of collection classes, eliminating the need to use C arrays, linked lists, and hashtables. There are three classes used for collecting Cocoa objects: NSArray for ordered collections of objects, NSSet for unordered collections, and NSDictionary for mapping key objects to value objects. These three collections are immutable — once initialized, they cannot be changed. If you want to add, delete, or otherwise change their contents, use the mutable subclasses NSMutableArray, NSMutableSet, and NSMutableDictionary.
The Touch part of Cocoa Touch is largely represented by the UIKit framework. This framework offers the drawing model, event-handling, application life-cycle, and other essentials for a touch-based application. You’ll largely interact with it through the various user interface component classes it provides: UIButton, UITextView, UITableView, and so on.
/ / Object
A unique occurance of a class is an instance. The actions that are performed on the instance are called methods.
Each instance or object contains not only information about its initial characteristics (data) , but also current characteristics (state).
Applying a method to an object can effect the state of an object.
This is the syntax to use to apply a method to an object
[ClassOrInstance method];
[recipient message];example:
myCar=[Car new];
[myCar drive];
[myCar getGas];
currentMileage=[myCar currentOdometer];
If you had an NSString instance called myString, you would get its third character with a methodinvocation like this:
myChar = [myString characterAtIndex: 3];
/ / Interface
When you define a new class, you have to do a few things. - Tell the Objective-C compiler where the class came from—Name its parent class
- Specify what type of data is to be stored in the objects of this class—describe the data that members of the class will contain (instance variables).
- Define the type of operations, or methods, that can be used when working with objects from
this class
@interface NewClassName: ParentClassName {
memberDeclarations;
}
methodDeclarations;
@end
class names begin with uppercase letter
example:
@interface Fraction: NSObject {
int numerator;
int denominator;
}
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
@end//Fraction
The leading - (dash) tells the Objective-C compiler that the method is an instance method. A + (plus sign) indicates a class method-one that performs some operation on itself—creating a new instance of itself.
example 2:
@interface Circle:NSObject{
ShapeColor fillColor;
ShapeRect bounds;
}
-(void) setFillColor: (ShapeColor) fillColor;
-(void) setBounds: (ShapeRect) bounds;
-(void) draw;
@end//Circle
/ / Return Values
You need to tell the compiler what type of information is returned by the method.
This declaration specifies that the instance method called retrieveNumerator returns an integer:
-(int) retrieveNumerator;
What does this return?
-(double) retrieveDoubleValue;
If a method returns no value, -(void) is used.
/ / Method Arguments
Method names end with a colon. This tells the compiler that the method expects to see an argument. If you do not include the colon, the compiler assumes that this method does not take any argument. The type of the argument specified is enclosed in a set of parentheses. The symbolic name to be used to identify that argument is displayed next:
methodType (returnType) methodName: (argumentType) argumentName;
- (void) setNumerator: (int) n;
setNumerator:
/ / @implementation
The @implementation section contains the code for the methods declared in the
@interface section.
Declare in the @interface
Define in the @implementation
Format for @implementation:
@implementation NewClassName
methodDefinitions;
@end
The methodDefinitions section contains code for each method specified in the @interface section. Each method's definition starts by identifying the type of method (class or instance), its return type and its argments and their types. The code for the method is surrounded by curly braces:
@implementation Fraction
-(void) print{
NSLog("%i/%i", numerator,denominator);
}
-(void) setNumerator: (int) n{
numerator=n;
}
-(void) setDenominator: (int) d{
denominator=d;
}
@end
example 2:
@implementation Circle
-(void) setFillColor:(ShapeColor) c{
fillColor=c;
}
-(void) setBounds: (ShapeRect) b{
bounds=b;
}
-(void) draw {
NSLog(@"drawing a circle at (%d %d %d %d) in %@",
bounds.x,bounds.y, bounds.with, bounds.height, colorName(fillColor));
}
@end//Circle
While you must provide a method definition for each method declaration in the @interface, you can also define methods that do not appear in the interface. These are refered to as private methods.
/ / Program
The program section contains the code to solve the particular problems and can be spread out over several files. This is where you'll find your main Method:
int main(int argc, char *argv[]){
NSAutoreleasePool * pool=[NSAutoreleasePool alloc] init];
Fraction *myFraction;
myFraction=[Fraction alloc];
myFraction=[Fraction init];
//myFraction=[[Fraction alloc] init];
//Fraction *myFraction=[[Fraction alloc] init];
[myFraction setNumerator:1];
[myFraction setDenominator:3];
NSLog(@"The value of myFraction is:");
[myFraction print];
[myFraction release];
[pool drain];
return 0;
}Fraction *myFraction says that myFraction is an object of type Fraction.
myFraction=[Fraction alloc]; creates myFraction by allocating memory storage space for the new fraction.
alloc is inhereted from the parent class
myFraction=[Fraction init]; initiallizes the new object.
[myFraction release]; clears space in memory
Here's a better program
@interface Fraction: NSObject {
int numerator;
int denominator;
}
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end
@implementation Fraction
-(void) print{
NSLog("%i/%i", numerator,denominator);
}
-(void) setNumerator: (int) n{
numerator=n;
}
-(void) setDenominator: (int) d{
denominator=d;
}
-(int) numerator{
return numerator;
}
-(int) denominator{
return denominator;
}
@end
int main(int argc, char *argv[]){
NSAutoreleasePool * pool=[NSAutoreleasePool alloc] init];
Fraction *myFraction=[[Fraction alloc] init];
[myFraction setNumerator:1];
[myFraction setDenominator:3];
NSLog(@"The value of myFraction is: %i/%i",[myFraction numerator], [myFraction denominator];
[myFraction release];
[pool drain];
return 0;
}Circle example:
@interface Circle:NSObject{
ShapeColor fillColor;
ShapeRect bounds;
}
-(void) setFillColor: (ShapeColor) fillColor;
-(void) setBounds: (ShapeRect) bounds;
-(void) draw;
@end//Circle
@implementation Circle
-(void) setFillColor:(ShapeColor) c{
fillColor=c;
}
-(void) setBounds: (ShapeRect) b{
bounds=b;
}
-(void) draw {
NSLog(@"drawing a circle at (%d %d %d %d) in %@",
bounds.x,bounds.y, bounds.with, bounds.height, colorName(fillColor));
}
@end//Circle
@interface Rectangle:NSObject{
ShapeColor fillColor;
ShapeRect bounds;
}
-(void) setFillColor: (ShapeColor) fillColor;
-(void) setBounds: (ShapeRect) bounds;
-(void) draw;
@end//Rectangle
@implementation Rectangle
-(void) setFillColor:(ShapeColor) c{
fillColor=c;
}
-(void) setBounds: (ShapeRect) b{
bounds=b;
}
-(void) draw {
NSLog(@"drawing a rectangle at (%d %d %d %d) in %@",
bounds.x,bounds.y, bounds.with, bounds.height, colorName(fillColor));
}
@end//Rectangle
@interface OblateSphereoid:NSObject{
ShapeColor fillColor;
ShapeRect bounds;
}
-(void) setFillColor: (ShapeColor) fillColor;
-(void) setBounds: (ShapeRect) bounds;
-(void) draw;
@end//OblateSphereoid
@implementation OblateSphereoid
-(void) setFillColor:(ShapeColor) c{
fillColor=c;
}
-(void) setBounds: (ShapeRect) b{
bounds=b;
}
-(void) draw {
NSLog(@"drawing a oblate sphereoid at (%d %d %d %d) in %@",
bounds.x,bounds.y, bounds.with, bounds.height, colorName(fillColor));
}
@end//OblateSphereoid
int main(int argc, char *argv[]){
id shapes[3];
ShapeRect rect0={0,0,10,30};
shapes[0]=[Circle new];
[shapes[0] setBounds:rect0];
[shapes[0] setFillColor:kRedColor];
ShapeRect rect1={30,40,50,60};
shapes[1]=[Rectangle new];
[shapes[1] setBounds: rect1];
[shapes[1] setFillColor:kGreenColor];
ShapeRect rect2={15,19,37,27};
shapes[2]=[OblateSphereoid new];
[shapes[2] setBounds: rect2];
[shapes[2] setFillColor:kBlueColor];
drawShapes (shapes,3);
return(0);
}//main
/ / Data Tyes
There are 4 types of constants in Objective-C:
- float
- double
- int
- char
Expressions cosisting of only constant values are referred to as constant expressions.
int
Do not use a comma when representing an integer. There are special formats that enable an integer to be expressed in base 8 and 16:
NSLog(@"octal format %o", num);
//with leading 0 and lowecase letters
NSLog(@"hex format %#x", num);
//without leading 0 and lowecase letters
NSLog(@"hex format %x", num);
//with leading 0 and uppercase letters
NSLog("hex format %#X", num);
//without leading 0 and uppercase letters
NSLog(@"hex format %X", num);
div class="bottomBorder">float
Values with decimal points. To display a float using scientific notation:
float num=2.5e-3;
NSLog(@"scientic notation %e",num);
double
char
Strings
Single characters are enclosed by single quotes and strings of characters are surrounded by double quotes. Most frameworks pass strings around in NSString objects. The NSString class provides an object wrapper for strings. It includes built-in memory management for storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more. Because such strings are used commonly though, Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand precede a normal, double-quoted string with the @ symbol, as shown in the following examples:NSString* myString = @"My String\n"; NSString* anotherString = [NSString stringWithFormat:@"%d %s", 1, @"String"]; // Create an Objective-C string from a C string NSString* fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];