Iphone Ilearn Beginners Developer Course
Iphone Ilearn Beginners Developer Course
Table of content
1. Introduction
2. iPhone OS Architecture & Technologies 3. Whats in the iPhone SDK? 4. Getting iPhone setup.
5. Object Basics
6. Objective-C Language 1. Messaging syntax 2. Objective-C Types 3. Working with Classes & Objects 4. Delegates and Memory Allocation 5. Foundation Classes 7. Create View Based Project Hello World Example 1. Connect Code to An Interface Builder 2. Update UI on events 3. Executing code 4. Analysis 8. Navigation Based Application 1. Adding Sub-View to UITableView 9. Windows Based Application
2
Introduction
iPhone OS is the operating system at the heart of iPhone and iPod touch devices.
The iPhone OS platform was built using the knowledge that went into the creation of Mac OS X, and many of the tools and technologies used for development on the platform have their roots in Mac OS X as well. Despite its similarities to Mac OS X, you do not need to be an experienced Mac OS X developer to write applications for iPhone OS. The iPhone Software Development Kit (SDK) provides everything you need to get started creating iPhone applications.
The iPhone SDK contains the tools needed to design, create, debug, and optimize software for iPhone OS. It also contains header files, sample code, and documentation for the platforms technologies. You can download the iPhone SDK from the members area of the iPhone Dev Center, which is located at http://developer.apple.com/iphone. Registration is required but free.
iPhone OS Architecture
iPhone OS is the operating system that runs on iPhone and iPod touch devices. This operating system manages the device hardware and also provides the basic technologies needed to implement native applications on the phone. The iPhone OS architecture is similar to the basic architecture found in Mac OS X. At the high level, iPhone OS acts as an intermediary between the iPhone and iPod touch hardware and the applications that appear on the screen, as shown in figure. Applications that you create never interact directly with the hardware but instead go through system interfaces, which interact with the appropriate drivers. This abstraction protects your application from changes to the underlying hardware. iPhone OS uses a fairly straightforward software stack. At the very bottom of this stack is the Mach kernel and hardware drivers, which manage the overall execution of programs on the device. On top of that layer are additional layers that contain the core technologies and interfaces you use for development. Although iPhone OS does not expose any of the kernel or driver-level interfaces, it does expose technologies at the higher levels of the stack.
The implementation of iPhone OS technologies can be viewed as a set of layers. At the lower layers of the system are the fundamental services on which all applications rely, while higher-level layers contain more sophisticated services and technologies. Whenever possible. Use higher-level frameworks in your program over lower-level. Higher-level frameworks provide object-oriented abstractions for lower-level constructs.
iPhone OS Technologies
iPhone Simulator Mac OS X application that simulates the iPhone technology stack, allowing you to test iPhone applications locally on your Intel based Macintosh computer.
&
Xcode and Instruments also let you interact directly with an attached device to run and debug your code on the target hardware. Development on an actual device requires signing up for Apples paid iPhone Developer Program and configuring a device for development purposes
Get the iPhone SDK Now that you have signed up for that, you will have access to the iPhone SDK, Documentation, Sample Code, and API. The first thing to do is download the iPhone SDK. This includes the latest version of XCode and contains the entire suite for developing iPhone applications. The installation is pretty strait forward. Just accept all of the defaults and youll be on your way.
Object Basics
OOP Vocabulary Class: defines the grouping of data and code, the type of an object. Instance: a specific allocation of a class. Method: a function that an object knows how to perform. Instance Variable (or ivar): a specific piece of data belonging to an object. Encapsulation : keep implementation private and separate from interface. Polymorphism : different objects, same interface. Inheritance : hierarchical organization, share code, customize or extend behaviors.
Tons of books and articles on OOP Most Java or C++ book have OOP introductions Objective-C 2.0 Programming Language http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
7
Objective-C
About Objective-C Strict superset of C. Mix C with ObjC Or even C++ with ObjC (usually referred to as ObjC++). A very simple language, but some new syntax. Single inheritance, classes inherit from one and only one superclass. Protocols define behavior that cross classes. Dynamic runtime & Loosely typed, if youd like. Syntax Additions Small number of additions Some new types Anonymous object Class Selectors Syntax for defining classes Syntax for message expressions. Dynamic Runtime Object creation All objects allocated out of the heap No stack based objects Message dispatch Introspection OOP From ObjC Perspective Everybody has their own spin on OOP. Apple is no different. For the spin on OOP from an ObjC perspective: Read the Object-Oriented Programming with Objective-C document. http://developer.apple.com/iphone/library/d ocumentation/Cocoa/Conceptual/OOP_ObjC Classes and Objects Classes declare state and behavior State (data) is maintained using instance variables Behavior is implemented using methods Instance variables typically hidden Accessible only using getter/setter methods. Classes and Instances In Objective-C, classes and instances are both objects. Class is the blueprint to create instances.
Message Syntax
To get an object to do something, you send it a message telling it to apply a method. In Objective-C, message expressions are enclosed in brackets: [receiver message] The receiver is an object, and the message tells it what to do. In source code, the message is simply the name of a method and any arguments that are passed to it. When a message is sent, the runtime system selects the appropriate method from the receivers repertoire and invokes it. For example, this message tells the myRectangle object to perform its display method, which causes the rectangle to display itself: [myRectangle display];
Messaging syntax
Class and Instance Methods Message examples Person *voter; //assume this exists [voter castBallot]; int theAge = [voter age]; Terminology [voter setAge:21]; if ([voter canLegallyVote ]) { // do something voter-y } Message expression [receiver method: argument] Instances respond to instance methods - (id)init; - (float)height; - (void)walk; Classes respond to class methods + (id)alloc; + (id)person; + (Person *)sharedPerson;
Message
[receiver method: argument] Selector [receiver method: argument] Method The code selected by a message.
10
10
Messaging syntax
Method definition examples Person *voter; //assume this exists Person * castBallot; [voter castBallot]; - (int)age; int theAge = [voter age]; - (void)setAge:(int)age; [voter setAge:21]; Dot Syntax Objective-C 2.0 introduced dot syntax Convenient shorthand for invoking accessor methods float height = [person height]; float height = person.height; [person setHeight:newHeight]; person.height = newHeight; Follows the dots. .. [[person child] setHeight:newHeight]; // exactly the same as person.child.height = newHeight;
- (BOOL)canLegallyVote;
if ([voter canLegallyVote]) { // do something voter-y } -( v o i d ) r e g i s t e r F o r S t a t e : ( N S S t r i n g * ) s t a t e party:(NSString*)party;
11
11
Objective-C Types
Dynamic and static typing Dynamically-typed object Just id Not id * (unless you really, really mean it) Statically-typed object Objective-C provides compile-time, not runtime, type checking Objective-C always uses dynamic binding BOOL typedef When ObjC was developed, C had no boolean type ObjC uses a typedef to define BOOL as a type Macros included for initialization and comparison: YES & NO
id anObject
BOOL flag = NO; if (flag == YES) if (flag) if (!flag) if (flag != YES) flag = YES; flag = 1;
Person *anObject
The null object pointer Test for nil explicitly Selectors identify methods by name A selector has type SEL
Or implicitly
Conceptually similar to function pointer Selectors include the name and all colons, for example:
12
12
Identity versus Equality Identitytesting equality of the pointer values if (object1 == object2) { NSLog(@"Same exact object instance"); } Equalitytesting object attributes if ([object1 isEqual: object2]) { NSLog(@"Logically equivalent, but may be different object instances"); }
13
13
A delegate is an object that usually reacts to some event in another object and/or can affect how another object behaves.
The objects work together for the greater good of completing a task. Typically a delegate object will be shared by many other objects that have a more specific task to carry out. The delegate itself will be more abstract and should be very reusable for different tasks. The object which contains the delegate typically sends the delegate a message when a triggered event occurs, giving the delegate an opportunity to carry out its specified task.
Example for De-allocation - (void)dealloc { [helloLabel release]; [nameField release]; [super dealloc]; }
14
14
Foundation Classes
Foundation Framework Value and collection classes User defaults Archiving Notifications Undo manager Tasks, timers, threads File system, pipes, I/O, bundles. String Constants In C constant strings are simple In ObjC, constant strings are @just as Constant strings are NSString instances
simple
NSObject Root class Implements many basics Memory management Introspection Object equality NSString General-purpose Unicode string support Unicode is a coding system which represents all of the worlds languages Consistently used throughout Cocoa Touch instead of char * Without doubt the most commonly used class Easy to support any language in the world with Cocoa.
NSString *aString = @Johnny; NSString *log = [NSString stringWithFormat: @Its %@, aString];
log would be set to Its Johnny.
NSLog(@I am a %@, I have %d items, [array className], [array count]); I am a NSArray, I have 5 items
15
15
Foundation Classes
NSString
16
Foundation Classes
NSMutableString NSMutableString subclasses NSString Allows a string to be modified Common NSMutableString methods + (id)string; - (void)appendString:(NSString *)string; - (void)appendFormat:(NSString *)format, ...; NSMutableString *newString = [NSMutableString string]; [newString appendString:@Hi]; [ n e w S t r i n g a p p e n d F o r m a t : @ , m y f a v o r i t e n u m b e r i s : % d , [self favoriteNumber]]; Collections Array - ordered collection of objects Dictionary - collection of key-value pairs Set - unordered collection of unique objects Common enumeration mechanism Immutable and mutable versions Immutable collections can be shared without side effect Prevents unexpected changes Mutable objects typically carry a performance overhead
17
17
Foundation Classes
NSArray Common NSArray methods + arrayWithObjects:(id)firstObj, ...; // nil terminated!!! (unsigned)count; (id)objectAtIndex:(unsigned)index; (unsigned)indexOfObject:(id)object;
NSNotFound returned for index if not found N S A r r a y * a r r a y = [ N S A r r a y a r r a y W i t h O b j e c t s : @ R e d , @ B l u e , @ G r e e n , n i l ] ; if ([array indexOfObject:@Purple] == NSNotFound) { NSLog (@No color purple); } Be careful of the nil termination!!! NSMutableArray NSMutableArray subclasses NSArray So, everything in NSArray Common NSMutableArray Methods + NSMutableArray *array = [NSMutableArray array]; [array [array [array [array addObject:@Red]; addObject:@Green]; addObject:@Blue]; removeObjectAtIndex:1];
18
Foundation Classes
NSDictionary - Common NSDictionary methods + dictionaryWithObjectsAndKeys: (id)firstObject, ...; - (unsigned)count; - (id)objectForKey:(id)key; nil returned if no object found for given key N S D i c t i o n a r y * c o l o r s = [ N S D i c t i o n a r y d i c t i o n a r y W i t h O b j e c t s A n d K e y s : @ R e d , @ C o l o r 1 , @ G r e e n , @ C o l o r 2 , @ B l u e , @ C o l o r 3 , n i l ] ; NSString *firstColor = [colors objectForKey:@Color 1]; if ([colors objectForKey:@Color 8]) { // wont make it here }
19
Foundation Classes
NSSet Unordered collection of objects Common NSSet methods
20
20
Foundation Classes
Enumeration Consistent way of enumerating over objects in collections Use with NSArray, NSDictionary, NSSet, etc. NSArray *array = ... ; // assume an array of People objects // old school Person *person; int count = [array count]; for (i = 0; i < count; i++) { person = [array objectAtIndex:i]; NSLog([person description]); } // new school for (Person *person in array) { NSLog([person description]); } NSNumber In Objective-C, you typically use standard C number types NSNumber is used to wrap C number types as objects Subclass of NSValue No mutable equivalent! Common NSNumber methods + + (NSNumber *)numberWithInt:(int)value; (NSNumber *)numberWithDouble:(double)value; (int)intValue ; (double)doubleValue ;
21
21
Foundation Classes
Other Classes NSData / NSMutableData Arbitrary sets of bytes NSDate / NSCalendarDate Times and dates
More ObjC Info? http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC Concepts in Objective C are applicable to any other OOP language
Thats it! Now we can move over to write our first Hello World application.
22
22
Create a New View Based Project Opening the iPhone Simulator Adding UI Elements to applications home screen Executing the code
23
24
25
Run Simulator
Click on the Build and Go button at the top of Xcode. The program should compile and launch the iPhone Simulator (see picture). Make sure the drop-down on the top left says Simulator | Debug, this tells Xcode that target is under test for iPhone simulator.
->
Now lets add some UI components to our view by editing the nib file ViewBasedViewController.xib in the Interface Builder.
26
Interface builder
A few notes about interface builder Library The right-most window contains all of your controls that you can add to your view. For this tutorial we will be using a Label. The next window to the left of that contains objects that we will connect our interface to. View represents the view of this nib file (basically the interface). Files Owner is the object that links the interface to the code. View - This is your user interface for your iPhone application. This window is where you will drop controls from the right-most window. Attributes This is where we will set the styling properties of our controls.
27
Execute code Go ahead and click Build and Go again to launch the iPhone Simulator. Your screens should look something like this. This is a simple iPhone application designed solely with the help of Interface Builder. The next step in iPhone application development is to Connect the Code to An Interface Builder View. That would be taken up in the next example.
28
The user will tap inside a text box which brings up the iPhones keyboard. The user will type their name using the keyboard. The user will press a button. The label will update with a greeting containing that users name. If the user fails to enter in text, the label will say something like Please Enter Your Name.
Create a new View-Based application Create a simple user interface Write code to connect to an interface Connect the interface to the code Update the interface based on user interaction.
We are learned, how to create a view based application in Hello World Example. Here, we would use same as our base application for further development.
29
The basic steps are same as in case of adding a Label. The first thing to do is drag a Text Field from the library box on to your view window. A set of blue lines will help to line up controls as well as center them. Once you have added the Text Field to the View, move it around until its in a suitable position. Next, stretch each side of the text box so that it spans across almost the entire view area. (The blue lines on the right and left will let you know when to stop.) Now we are going to set some of the attributes of the Text Field. If the Attributes Inspector doesnt appear, click on the Text Field and then click Tools -> Attributes Inspector.
30
For Return Key Select Done. This makes the return key on the keyboard say Done rather than return. Also, make sure Clear When Edit Begins is checked
31
We are now done creating our interface. It should look something like this.
32
Connect Code to An Interface Builder Example 2 :interface to some code are called View Controllers. Lets open up Connection Code The files that link an
ViewBasedViewController.h. This is the file where we will declare all of our interface variables. Add the following code to you ViewBasedViewController.h.
33
The purpose of making declared Variables as Properties is to allow us to set certain attributes
that are associated with the variables.
Retain tells the compiler that we will handle the memory management of this object (dont forget
to release it when you are done). Otherwise it will get cleaned after being instantiated.
- (IBAction) updateText:(id) sender; =>This is the function that will get called when the
user presses the button that was created in Interface Builder. We are simply declaring it here in the header file. We will implement this function in later slides. Now, we need to connect the interface to the code.
34
35
36
Click on the Label in your View window to select it. Click Tools -> Connections Inspector. You will now see a circle next to New Referencing Outlet. Click in that circle and drag it over to the Files Owner object. A message will pop up with lblHello. Click on lblHello and the connection is made. You should now see:
37
Click on the Button in your View window to select it. Click Tools -> Connections Inspector. You will now see a circle next to Touch Up Inside. This is the trigger that gets called when a user presses the button. Click in that circle and drag it over to the Files Owner object. A message will pop up with updateText. Click on updateText and the connection is made. You should now see:
Now all of the connections should be set up. Go ahead and close Interface Builder.
38
Update UI on events
Open up the file ViewBasedViewController.m . This is the file where we will implement the updateText function. Add the following code. Code is explained in following slides.
39
Update UI on events
Line wise Code Explanation:
@synthesize txtName,lblHello; => Most of the time when creating (private) variables, getter and setter methods need to be specified. Theses functions get the value of a variable and set the value of a variable. What synthesize does is creates these methods. Next we will implement our updateText method. Here, it is started by creating a temporary string. This is the string that we will insert into the text of the label. The next line checks to see if the user has entered any text into the Text Field. txtName.text returns an NSString. We are simply calling the length method on a string. If the length is 0, then obviously the user has not entered any text. If this is the case, we set the temporary string to Please enter your name: instructing the user to enter in their name. If the user has entered in some text, a new string is allocated. The initWithFormat method is similar to printf in C. So, the string Hello %@! is used. The %@ in the string means we will be substituting it for a string. To get the value of the Text Field we again use the txtName.text property. Finally, the value of the Label is set by calling lblHello.text. This calls the text property of label and sets the text to our temporary string variable. The last line [text release]; releases the temporary text field from memory. This is necessary to write an efficient iPhone application. If this step is omitted, it would lead to iPhone apps crash.
Executing code
Click Build and Go. The application should launch in the iPhone Simulator. When the inside of the Text Field clicked, it should bring up the iPhones keyboard (you can also type with your keyboard). Enter in your name and click Display. Here are a few screens of what your app should look like. (following slides...) Case 1: - User Clicks Display without typing in their name. Case 2 :-User types in their name and clicks Display.
41
Analysis
After studying examples, we are now aware
how to develop a view based application. how to add components to UI through Interface builder. Write code to connect to an interface. Connect the interface to the code A few ways to update the interface based on user interaction.
In the next example, we would learn about a simple navigation based application.
42
Create Project Create a New Navigation-Based Application Click Xcode > New Project and a window should pop up (see picture). Make sure Application is selected under iPhone OS. Select Navigation-Based Application and Choose. Name this project as Hello World.
43
Update UITableView Cells Open RootViewController.m file. This is the view controller that Apple added to our main view. This files, in this case, would contain functions that have been overridden from the Table View super class. Since we are editing a table, all of these functions will be related to editing a table. Find the function called numberOfRowsInSection.
This function tells the application how many rows are in our table. Currently, it returns 0. Lets change that to return 1. This will tell the application that we want 1 row in our table.
44
45
We are basically calling the setText method of the cell object and pass in the string Hello World. Please
Thats it! Click the Build and Go button again to launch the iPhone simulator.
46
47
Add a Sub-view to a UITableView. This sub-view will consist of three key elements. A Header File (*.h file extension) An Implementation File (*.m file extension) An Interface File (*.xib extension)
48
49
Click Finish.
50
51
52
The code below will do the following: Sets up an array of views and supplies that array to our UITable as a data source Adds multiple sub views to our application using the sub view weve designed and written thus far Allows us to navigate to different sub views upon view selection from our UITableView Open the file RootViewController.h and add the following code:
53
54
Execute
Click the Build and Go button in XCode. Our application thus far should now allow us to select a sub view and navigate to it. The application should look as shown here.
56
57
To deploy the application on iPhone device you must have valid certificate or authorization to compile and run your application. In iPhone terminology they are called as Steps required to get the certificate. Go to http://developer.apple.com/iphone/index.action and register your self with valid user. login & go to link @iPhone Provision Portal Follow the steps as described on the portal to generate certificate from your
Mac machine and Provision file required to run your application in iPhone
device.
58
Note: If you have a noncompliant private key highlighted in the Keychain during this process, the resulting Certificate Request will not be accepted by the Provisioning Portal. Confirm that you are selecting Request a Certificate From a Certificate Authority... and not selecting Request a Certificate From a Certificate Authority with <Private Key>
In the User Email Address field, enter your email address. Please ensure that the email address entered matches the information that was submitted when you registered as an iPhone Developer.
59
61
62
63
64
Thank You!
Happy Learning!
65
65