0% found this document useful (0 votes)
143 views65 pages

Iphone Ilearn Beginners Developer Course

SEG Academy Achieving Capability Excellence iPhone Developer Training Table of content 1. Introduction 2. iPhone OS Architecture & Technologies 3. What‘s 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. Executin

Uploaded by

Sumantra Joshi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views65 pages

Iphone Ilearn Beginners Developer Course

SEG Academy Achieving Capability Excellence iPhone Developer Training Table of content 1. Introduction 2. iPhone OS Architecture & Technologies 3. What‘s 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. Executin

Uploaded by

Sumantra Joshi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

SEG Academy

Achieving Capability Excellence

iPhone Developer Training

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 & Technologies

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.

Applications layered on top of iPhone OS

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

Whats in the iPhone SDK?


XCode Tools Provides tools that support iPhone application development, including the following key applications: XCode - an integrated development environment that manages your application projects and lets you edit, compile, run, and debug your code. Interface Builder - a tool you use to assemble your user interface visually. The interface objects you create are then saved to a resource file format and loaded into your application at runtime. Instruments - a runtime performance analysis and debugging tool. You can use Instruments to gather information about your applications runtime behavior and identify potential problems. iPhone Reference Library SDK includes reference documentation for iPhone OS by default and you can download more complete version of the iPhone Reference Library by subscribing to the iPhone OS Library doc set. From Xcode, choose Help > Documentation and then click the subscribe button next to the iPhone OS Library doc set in the left-hand column.

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

Getting iPhone setup


What Can You Create? Users can run two different types of custom applications on a device: web applications and native applications. Web applications use a combination of HTML, cascading style sheets, and JavaScript code to implement interactive applications that live on a web server and are transmitted over the network and run inside the Safari web browser. Native applications, on the other hand, are installed directly on the device and can run without the presence of a network connection. The iPhone SDK supports the creation of native foreground applications that appear on the devices Home screen only. It does not support the creation of other types of code, such as drivers, background applications, frameworks, or dynamic libraries. If you want to integrate code from a framework or dynamic library into your application, you should link that code statically into your applications executable file when building your project. Sign Up For a Developer Account Head on over to Apple Developer Connection and sign up for a developer account. You can sign up for an account for free to be able to gain access to all of the tools and documentation. This will also provide you with a built-in iPhone simulator so that you can test your applications on your local machine. However, when you are ready to deploy your application on an iPhone, you must sign up for the iPhone Developer Program.

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.

More OOP Info?

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];

Message syntax [receiver message] [receiver message:argument] [receiver message:arg1 andArg:arg2]

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;

[voter registerForState:@"CA" party:@"Independant"]; - (Person*)spouse; -( N S S t r i n g * ) n a m e ; NSString *name = [[voter spouse] name];

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

if (person == nil) return;


if (!person) return;

Can use in assignments and as arguments if expected

SEL action = [button action]; [button setAction:@selector(start:)];

Sending a message to nil?

person = nil; [ b u t t o n s e t Ta r g e t : n i l ] ; person = nil; [person castBallot];

Conceptually similar to function pointer Selectors include the name and all colons, for example:

-(void)setName:(NSString *)name age:(int)age; SEL sel = @selector(setName:age:);

would have a selector:

12

12

Working with Classes & Objects


Class Introspection You can ask an object about its class Class myClass = [myObject class]; NSLog(@"My class is %@", [myObject className]); Testing for general class membership (subclasses included): if ([myObject isKindOfClass:[UIControl class]]){ // something } Testing for specific class membership (subclasses excluded): if ([myObject isMemberOfClass:[NSString class]]) { // something string specific } -description NSObject implements description - (NSString *)description; Objects represented in format strings using %@ When an object appears in a format string, it is asked for its description [NSString stringWithFormat: @The answer is: %@, myObject]; You can log an objects description with: NSLog([anObject description]); Your custom subclasses can override description to return more specific information

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

Delegates and Memory Allocation


Customizing Behaviour with Delegation? The idea of delegation is that an object can have a single delegate object that it will call when certain events occur. Memory Allocation

Objects are created dynamically through the keyword, alloc


Objects are dynamically deallocated using the words release and autorelease autorelease deallocates the object once it goes out of scope. NOTE: None of these words are built-in

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

NSString *aString = @Hello World!;

Format Strings Similar to printf, but with %@ added for objects

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.

Also used for logging

NSLog(@I am a %@, I have %d items, [array className], [array count]); I am a NSArray, I have 5 items

would log something like:

15

15

Foundation Classes
NSString

Often ask an existing string for a new string with modifications


- (NSString *)stringByAppendingString:(NSString *)string; - (NSString *)stringByAppendingFormat:(NSString *)string; - (NSString *)stringByDeletingPathComponent; Example:

NSString *myString = @Hello; NSString *fullString; fullString = [myString stringByAppendingString :@ world!];


fullString would be set to Hello world! Common NSString methods

- ( B O O L ) i s E q u a l To S t r i n g : ( N S S t r i n g * ) s t r i n g ; - (BOOL)hasPrefix:(NSString *)string; - (int)intValue ; -( d o u b l e ) d o u b l e V a l u e ;


Example: NSString *myString = @Hello; NSString *otherString = @449; if ([myString hasPrefix:@He]) { // will make it here } if ([otherString intValue ] > 500) { // wont make it here }
16

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];

(NSMutableArray *)array; (void)addObject:(id)object; (void)removeObject:(id)object; (void)removeAllObjects; (void)insertObject:(id)object atIndex:(unsigned)index;


18

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 }

NSMutableDictionary - NSMutableDictionary subclasses NSDictionary Common NSMutableDictionary methods


+ (NSMutableDictionary *)dictionary; (void)setObject:(id)object forKey:(id)key; (void)removeObjectForKey:(id)key; (void)removeAllObjects;

NSMutableDictionary *colors = [NSMutableDictionary dictionary]; [colors setObject:@Orange forKey:@HighlightColor];


19

19

Foundation Classes
NSSet Unordered collection of objects Common NSSet methods

+ setWithObjects:(id)firstObj, ...; // nil terminated - (unsigned)count; - (BOOL)containsObject:(id)object;


NSMutableSet NSMutableSet subclasses NSSet Common NSMutableSet methods + (NSMutableSet *)set; (void)addObject:(id)object; (void)removeObject:(id)object; (void)removeAllObjects; (void)intersectSet:(NSSet *)otherSet; (void)minusSet:(NSSet *)otherSet;

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

Getting some objects


Use class factory methods NSStrings +stringWithFormat: NSArrays +array NSDictionarys +dictionary

Or any method that returns an object except alloc/init or copy.

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 View Based Project Hello World Example


This Hello World application will demonstrate how to work with Interface Builder to create a simple layout for an application. In fact, it wont require any code to be written at all. In this tutorial you will learn:

Create a New View Based Project Opening the iPhone Simulator Adding UI Elements to applications home screen Executing the code

23

Create View Based Project Hello World Example


Create a New View Based Project Open Xcode. Click on File > New Project.

Make sure that Application is


highlighted under iPhone OS. Select View-Based Application. Name this project ViewBased.

24

Create View Based Project Hello World Example


Default Files At this point, Apple has added some default files to get us started.
CoreGraphics.framework, Foundation.framwork, UIKit.framework This is a set of library functions provided by Apple that we use in our application. We use these as includes similar to any other language that includes library functions. <appname>.app This is your app that gets installed on the iPhone. <appname>_Prefix.pch This is another include file that gets compiled separately from your other files so you dont need to include it on each file. It contains some code to include the data inside the frameworks. <appname>AppDelegate.h This is a header file that contains all of our definitions for variables that we will be using. Its very similar to a header file in C or C++. <appname>AppDelegate.m Consider this file our starting point for execution. The main.m file invokes this object. Info.plist This contains various meta information about your program. There isnt really a need to edit this until we are ready to start testing on the iPhone. main.m Like most programming language, this file contains our main function. This is where execution begins. The main function basically instantiates our object and starts the program. In usual circumstances, one shouldnt need to edit this file. MainWindow.xib This contains the visual information of our main window. If double clicked, it will open in a program called Interface Builder. We will get to this a little later. Just on thing to note is this file does not contain any code. RootViewController.h, RootViewController.m - These are files for a view controller that gets added to our main window. For example, Apple has already created a simple interface when you clicked on Navigation-Based Application. Since most navigation-based applications use a Table View, Apple also provides a Table View for us to use. RootViewController.xib This is a view that would be used by us to add UI components. We will be displaying our Hello World text in one such component added.

25

Create View Based Project Hello World Example


Apple have added the main window for us to edit along with the code to launch the window. In iPhone terms, each window is called a View. Since only one view can be seen at a time, a new view needs to be created for each screen in an application. In this example, we will be sticking to editing the view Apple has provided us. Go ahead and click Build and Go.

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

Create View Based Project Hello World Example


Adding UI Elements using interface builder
Adding UI Elements to Home Screen
Double click on ViewBasedViewController.xib. This is a nib file that opens with Interface Builder. ViewBasedViewController.xib contains information regarding the layout and controls of our view. (see picture).

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

Create View Based Project Hello World Example


Add a Label Drag a Label from the from the library box on to your view window. You will see some blue lines to guide you. These are in place to help line up controls as well as center them. Once you have added the Label to the View, move it around until its in a position that you are happy with. After you have added the Label, click on it, and then click Tools -> Attributes Inspector (see pic). In the Text field type in Hello World. Now press Apple-S to save this file. We are done with Interface Builder so you can close it. The application is now ready to be executed.

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

Connect Code to An Interface Builder


This example would demonstrate how to create an UI using Interface Builder and connect it to the code. We will create UITextField, UILabel, and a Button. Heres how the application will work:

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.

This example would incorporate the following activities:

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

Connect Code to An Interface Builder


Create a simple user interface Modify the Hello World Example as given in following steps: Open Interface Builder. Open Attributes Inspector for Label and change the text Hello World to Enter your name above (or below, as per the Label position with respect to Text Field for name). Now we need to add other screen elements, viz. , a Text Field, and a Button. Add a Text Field

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

Connect Code to An Interface Builder


Add a Text Field Attributes In the Placeholder field type in Name. This is the default text that appears in the Text Field before a user types anything. For Capitalize select Words This tells XCode that we want to capitalize each word. Add a Button Drag a Button from the library onto your view. Stretch it and position it however you would like. Add some text to the Button. Click on the button and then click Tools -> Attributes Inspector. In the Title field, type Display.

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

Connect Code to An Interface Builder

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

Connect Code to An Interface Builder


Code Explanation:

Example 2 : Connection Code


Interface Builder uses IBOutlets and IBActions to connect to the code. IBOutlet UITextField *textName creates an outlet to connect to the text field we created in interface builder. We use this variable to get information from the text field. IBOutlet UILabel *lblHello An outlet that connects our label on our interface to the code. This variable is used to set the value of the label. Now that we have declared these variables, we need to make them properties.

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

Connect Code to An Interface Builder


Connect the interface to the code Double click on ViewBasedViewController.xib again to open up Interface Builder. Connect the View Click anywhere on the background of your view (anywhere that is not the Text Field, Label, or Button). Click Tools -> Connections Inspector. Next to New Referencing Outlet, you will see a circle. Click in that circle and drag the blue line to the Files Owner object and release it. The word view should pop up. Click on it to make connection.

35

Connect Code to An Interface Builder


Connect the Text Field

Example 2 : Connect Interface to Code


Click on the Text Field 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 txtName. Click on txtName and the connection is made. You should now see:

36

Connect Code to An Interface Builder


Connect the Label

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

Connect Code to An Interface Builder


Connect the Button

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.

Thats it! Click Build and Go.


40

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

Navigation Based Application


This example, again, is a Hello World application. However this time, the application design has been modified. In this example we would learn how to: Create a New Navigation-Based Application. Update the UITableView Cells to Display Hello World Text.

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

Navigation Based Application


Create a New Navigation-Based Application (continued) Click on the Build and Go button at the top of Xcode. It shows is the Table View that Apple has added for us (see picture). Table View is added by default for Navigation based Application. We would add a row to this table view, and display Hello World in it.

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

Navigation Based Application


Update UITableView Cells (continued) Locate the function cellForRowAtIndexPath. This function gets called once for every row. This is where we define what content to display in a given row. In this case we want the row to be a string that says Hello World.

45

Navigation Based Application


Update UITableView Cells (continued) cellForRowAtIndexPath function creates a new cell object and returns it. The code between the if(cell==null) block checks to see if we have created a cell before, if not build a new cell, otherwise use the one we created before. Right before the // Set up the cell comment add the following code: [cell setText:@"Hello World"];.

We are basically calling the setText method of the cell object and pass in the string Hello World. Please

refer to Apples Objective-C overview for string syntax details.

Thats it! Click the Build and Go button again to launch the iPhone simulator.
46

Navigation Based Application


Execute Click the Build and Go. You should now see a screen as shown (see picture). This example would now be used as a base for creating a Navigation Based application involving more then one view.

47

Adding Sub-View to UITableView


In the previous example, we learned about navigation based application. Using that knowledge, let us now design a navigation based application, with more then one view. In this application we would learn to :

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)

Create Project Create a New Navigation-Based Application


This has already been explained in last example. Name this project as BasicNavigation. Once again note that Table View is added by default for Navigation based Application.

48

Adding Sub-View to UITableView


Adding a Sub-view (Designed in Interface Builder) to a UITableView Open XCode. Right-click on the Classes folder within the project area on the left,

and select Add,


then New File. You will be presented with the following dialogue(see picture).

49

Adding Sub-View to UITableView


Adding a Sub-view to a UITableView (continued) Make sure Cocoa Touch Classes is selected on the left and UIViewController subclass is selected as the file template, and click Next (see picture in last slide).

A dialog box is displayed (see picture).


Name this file SubViewOneController.m. Make sure the checkbox for Also create SubViewOneController.h is checked.

Click Finish.

50

Adding Sub-View to UITableView


Adding a Sub-view to a UITableView (continued) The contents of the project window should now look similar to the illustration as shown (see picture).

51

Adding Sub-View to UITableView


Adding Contents to Sub-View Now we would create a user interface to go with our view controller code. Steps to create a User Interface has been given in previous examples. Drag a UILabel and a UIButton such that our view mimics the following interface.

52

Adding Sub-View to UITableView


Connecting Sub-View to UITableView At this point weve created our first sub-view, however were not going to be able to get to it from application just yet. Before moving on, we should go back into XCode and click on Build before moving onto the next part. The build should compile and the results should report back successfully at this point.

Navigating to a Sub-View from a UITableView

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

Adding Sub-View to UITableView


Navigating to a Sub-View from a UITableView Open the file RootViewController.m and add the following code:

54

Adding Sub-View to UITableView


Navigating to a Sub-View from a UITableView (Add Code )

That completes our navigation code.


55

Adding Sub-View to UITableView

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

Windows Based Application


UIWindow Class Windows in this context essentially provide a surface area on the screen onto which the application can present information and controls to the user. The user does not see or interact directly with the UIWindow object. These windows may be created programmatically, but are typically created automatically by Interface Builder when you design your user interface. View Types The Window: The UIWindow is the root view of the view hierarchy and provides the surface on which all subviews draw their content. Container Views: Container views enhance the functionality of other view objects. The UIScrollView class, for example, provides scrollbars and scrolling functionality for the UITableView and UITextView classes. Controls: The controls category encompasses views that both present information and respond to user interaction. The difference between View-based and Windowbased templates: A View template gives you a Window template with a UIView already added and configured to display in the window, while the Window template gives you a blank slate with no default view set up. Display Views: Display views do not respond to user interaction. Examples of views in this category include the UILabel and UIImageView classes. Alert Views: The UIAlertView class displays a blue popup box on the screen and the UIActionSheet causes a panel to slide up from the bottom of the screen.

57

Deploying Application on iPhone Device


Certificate & Provisioning files

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

Deploying Application on iPhone Device


Generating a Certificate To request an iPhone Development Certificate, you first need to generate a Certificate Signing Request (CSR) utilizing the Keychain Access application in Mac OS X Leopard. The creation of a CSR will prompt Keychain Access to simultaneously generate your public and private key pair establishing your iPhone Developer identity. Private key is stored in the login Keychain by default & can be viewed in the Keychain Access application under the Keys category. To generate a CSR. In your Applications folder, open the Utilities folder and launch Keychain Access. In the Preferences menu, set Online Certificate Status Protocol (OSCP) and Certificate RevocationList (CRL) to Off. Choose Keychain Access -> Certificate Assistant -> Request a Certificate from a Certificate Authority.

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

Deploying Application on iPhone Device


Generating a Certificate (contd) In the Common Name field enter your name. Please ensure that the name entered matches the information that was submitted when you registered as an iPhone Developer. No CA (Certificate Authority) Email Address is required. The Required message will be removed after completing the following step. Select the Saved to Disk radio button and if prompted, select Let me specify key pair information and click Continue. If Let me specify key pair was selected, specify a file name and click Save. In the following screen select 2048 bits for the Key Size and RSA for the Algorithm. Click Continue. The Certificate Assistant will create a CSR file on your desktop. Uploading Certificate for Approval and Approving Certificate. After creating a CSR, log in to the iPhone Provisioning Portal and navigate to Certificates > Development and click Add Certificate.
60

Deploying Application on iPhone Device


Generating a Certificate (contd) Click the Choose file button, select your CSR and click Submit. If the Key Size was not set to 2048 bits during the CSR creation process, the Portal will reject the CSR. Once your CSR is approved or rejected, you will get information by email. Now Download and Install Development Certificates by simple double clicking that file on Mac machine.

61

Deploying Application on iPhone Device


Generating a Certificate (contd) Click the Choose file button, select your CSR and click Submit. If the Key Size was not set to 2048 bits during the CSR creation process, the Portal will reject the CSR. Once your CSR is approved or rejected, you will get information by email. Now Download and Install Development Certificates by simple double clicking that file on Mac machine.

62

Deploying Application on iPhone Device


Run the application
One of the main factors that determine how Xcode builds your application is the SDK used to build it. iPhone SDKs come in two families: one to target devices and one to target iPhone Simulator. Applications built using an SDK from the iPhone Device SDK family can run only on iOSbased devices. Conversely, applications built using an SDK from the iPhone Simulator SDK family run only in iPhone Simulator. Specify the SDK Xcode uses to build your application in your projects Base SDK build setting, which you can set in the General pane of the Project Info window or in the Build pane of the Project or Target Info window.

Setting Your Code Signing Identity


When you build your application to run it on a device, Xcode signs it with a development certificate (also known as a code signing identity) stored on your keychain. To learn how to obtain and install development certificates, see Preparing Your Mac for iOS Development. The Code Signing Identity build setting specifies the code signing identity Xcode uses to sign your binary. Xcode looks for code signing identities in your default keychain. Below snap shot shows an example set of options for the Code Signing Identity build setting obtained from the login (default) keychain (the name of the default keychain appears bold in the Keychains list).

63

Deploying Application on iPhone Device


These are the possible values for the Code Signing Identity build setting Dont Code Sign. Choose this option if you dont want to sign your binary. Note that with this value, when you build your applications using the iPhone Device SDK the build fails. Automatic Profile Selectors. These choices look for an identity whose name starts with iPhone Developer or iPhone Distribution. A code signing identity. A specific code signing identity. The code signing identities in your default keychain are listed under the name of the provisioning profile under which you downloaded them from the iPhone Provisioning Portal. Expired or otherwise invalid identities are dimmed and cannot be chosen. Xcode project templates are configured to use the iPhone Developer automatic selector. Refer to http://mobiforge.com/developing/story/deploying-iphone-apps-real-devices for more information on How to deploy iPhone App on device Build and run the application on device Happy Coding.

64

Thank You!

Happy Learning!

65

65

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy