This document provides an overview of Objective-C and teaches the basics of the language through examples. It covers Objective-C classes and objects, variables and data types, flow control and loops, methods, and more. The document is split into three parts, with each part building upon the previous concepts and adding new material to learn Objective-C programming.
3. An overview of Objective C
Learning how to develop software can be one of the
most intimidating prospects for any computer
enthusiast, and with the growing saturation of
applications in mobile marketplaces, it is becoming
increasingly difficult to get your work noticed.
That’s what this series is for, helping you learn ios
development from a conceptual perspective. No prior
knowledge of computer programming will be necessary.
Over the coming weeks, we’ll examine the iPhone’s
ability to deliver immersive, intuitive content, a unique
opportunity for both developers and consumers.
4. A Brief History of Objective-C
◦ Objective-C can be traced back to the early 1980s.
◦ Building upon Smalltalk, one of the first object-oriented
language, Cox’s fascination with problems of
reusability in software design and programming
resulted in the creation of the language.
◦ Recognizing that compatibility with C was crucial to
the success of the project, Cox began writing a pre-
processor for C to add backward compatibility with
C, which soon grew into an object-oriented extension
to the C language.
5. Conti
In 1986, Cox published a book about the language entitled Object-
Oriented Programming, An Evolutionary Approach.
Although the main focus of the instructional text was to point out the
issue of reusability, Objective-C has been compared feature-for-
feature with the major players in the programming game every since.
After Steve Jobs’ departure from Apple, he started a new company
called NeXT.
In 1988, NeXT licensed Objective-C from the owner of the
trademark, releasing its own Objective-C compiler and libraries on
which the NeXTstep UI and interface builder were based.
The innovative nature of this graphics-based interface creation
resulted in the creation of the first web browser on a NeXTstep
system.
6. Cont..
◦ At the Worldwide Developers Conference in 2006, Apple
announced Objective-C 2.0, a revision of Objective-C that
included syntax enhancements, performance
improvements, and 64-bit support.
◦ Mac OS X officially included a 2.0-enabled compiler in
October 2007.
◦ It is unclear at this time whether these language changes
will be available in the GNU runtime, or if they will be
implemented to be compliant with the larger Objective-C
2.0 standard.
7. Differentiates Objective-C from Other C
Languages?
Objective-C is essentially an extremely thin layer on top of
C, making it a superset of the language.
Moreover, it is possible to compile any C program with an
Objective-C compiler, including C code within an Objective-C
class.
All non-object-oriented syntax operations are derived from
C, while the object-orientation features an implementation akin
to Smalltalk messaging.
8. Cont…
◦ Messages - Object-oriented programming is based on
message passing to object instances. Objective-C does not
call methods, but rather will send a message.
◦
◦ The target of the message is resolved at runtime, with the
receiving object interpreting the message.
◦ The object to which the message is directed is not
guaranteed to respond to a message, and if it does not, it
simply raises an exception
9. Interfaces and
Implementations
Objective-C requires that the implementation of a class be in
separately declared code blocks, which has led developers to
the convention to place interface in the .h header file and
implementation in suffixed with .m, similar to those found in C.
10. Cont..
The implementation method is found within files designated
with the suffix .m, which are written using interface
declarations. Internal representations of a method vary
between different implementations, but the internal names of
the function are rarely used directly. Messages are converted
to function calls defined in the Objective-C runtime library.
11. Cont..
Dynamic Typing –
Like Smalltalk, Objective-C can send a message to an object
that is not specified in the interface, allowing for increased
flexibility.
This behavior is known as message forwarding and sometimes
delegation.
An error can be used in case the message cannot be
forwarded and messages that are never received can silently
drop into the background.
Static typing information can be optionally added to
variables, which is checked during compilation.
12. Cont..
Instantiation –
Once a class is written, it can be instantiated, meaning that a
copy of an object is captured in an instance, which share the
same attributes, but the specific information within these
attributes differ.
An example of this would be if you were to create a class
called “Employee,” describing all attributes common to
employees.
They all have names and salaries, but they differ in the
numerous cases that will show up.
14. Objective-C Data Types and
Variables
One of the fundamentals of any program involves data, and
programming languages such as Objective-C define a set of
data types that allow us to work with data in a format we
understand when writing a computer program.
For example, if we want to store a number in an Objective-C
program we could do so with syntax similar to the following:
Syantax
int mynumber = 10;
15. Objective-C Expressions
Now that we have looked at variables and data types we
need to look at how we work with this data in an application.
The primary method for working with data is in the form of
expressions.
int myresult = 1 + 2;
16. Operator Description
x += y Add x to y and place result in x
x -= y Subtract y from x and place result in x
x *= y Multiply x by y and place result in x
x /= y Divide x by y and place result in x
x %= y Perform Modulo on x and y and place result in x
x &= y Assign to x the result of logical AND operation on x
and y
x |= y Assign to x the result of logical OR operation on x
and y
x ^= y Assign to x the result of logical Exclusive OR on x
and y
Objective-C supports the following compound assignment
operators:
17. Objective-C Flow Control with if
and else
Such decisions define which code gets executed
and, conversely, which code gets by-passed when the program
is executing.
his is often referred to as flow control since it controls the flow
of program execution.
The if statement is perhaps the most basic of flow control
options available to the Objective-C programmer.
The basic syntax of the Objective-C if statement is as follows:
if (boolean expression) {
// Objective-C code to be performed when expression evaluates
to true
}
18. Looping with the for Statement
The syntax of an Objective-C for loop is as follows:
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
// statements to be executed
}
The initializer typically initializes a counter variable.
Traditionally the variable name i is used for this
purpose, though any valid variable name will do.
19. Objective-C Looping with do and
while
◦ The Objective-C for loop described previously works well
when you know in advance how many times a particular task
needs to be repeated in a program.
◦ There will, however, be instances where code needs to be
repeated until a certain condition is met, with no way of
knowing in advance how many repetitions are going to be
needed to meet that criteria.
◦ To address this need, Objective-C provides the while loop.
◦ The while loop syntax is defined follows:
while (''condition'')
{
// Objective-C statements go here
}
20. Objective-C do ... while loops
◦ It is often helpful to think of the do ... while loop as an inverted
while loop. The while loop evaluates an expression before
executing the code contained in the body of the loop.
◦ If the expression evaluates to false on the first check then the
code is not executed. The do ... while loop, on the other hand, is
provided for situations where you know that the code contained in
the body of the loop will always need to be executed at least
once.
◦ The syntax of the do ... while loop is as follows:
do
{
// Objective-C statements here
} while (''conditional expression'')
22. Object
Objects are self-contained modules of functionality that
can be easily used, and re-used as the building blocks
for a software application.
Objects consist of data variables and functions (called
methods) that can be accessed and called on the object
to perform tasks.
These are collectively referred to as members.
23. Class
Much as a blueprint or architect's drawing defines what an
item or a building will look like once it has been
constructed, a class defines what an object will look like
when it is created.
It defines, for example, what the methods will do and what
the member variables will be.
24. Declaring an Objective-C Class
Interface
Before an object can be instantiated we first need to define the class
'blueprint' for the object.
In this chapter we will create a Bank Account class to demonstrate the
basic concepts of Objective-C object oriented programming.
An Objective-C class is defined in terms of an interface and an
implementation.
In the interface section of the definition we specify the base class from
which the new class is derived and also define the members and methods
that the class will contain. The syntax for the interface section of a class is
as follows:
@interface NewClassName: ParentClass {
ClassMembers;
}
ClassMethods;
@end
25. Cont..
The ClassMethods section defines the methods that are
available to be called on the class.
These are essentially functions specific to the class that
perform a particular operation when called upon.
To create an example outline interface section for our
BankAccount class, we would use the following
@interface BankAccount: NSObject
{}
@end
26. Adding Instance Variables to a
Class
A key goal of object oriented programming is a concept referred to as
data encapsulation.
The idea behind data encapsulation is that data should be stored within
classes and accessed only through methods defined in that class.
Data encapsulated in a class are referred to as instance variables.
Instances of our BankAccount class will be required to store some
data, specifically a bank account number and the balance currently held
by the account.
Instance variables are declared in the same way any other variables
are declared in Objective-C. We can, therefore, add these variables as
follows:
@interface BankAccount: NSObject
{
double accountBalance;
long accountNumber;
}
@end
27. Define Class Methods
The methods of a class are essentially code routines that can
be called upon to perform specific tasks within the context of
an instance of that class.
Methods come in two different forms, class methods and
instance methods.
Class methods operate at the level of the class, such as
creating a new instance of a class.
Instance methods, on the other hand, operate only on the
instance of a class (for example performing an arithmetic
operation on two instance variables and returning the result).
Class methods are preceded by a plus (+) sign in the
declaration and instance methods are preceded by a minus (-)
sign.
-(void) setAccountNumber: (long) y;
28. Declaring an Objective-C Class
Implementation
The next step in creating a new class in Objective-C is to write the
code for the methods we have already declared.
This is performed in the @implementation section of the class
definition.An outline implementation is structured as follows:
@implementation NewClassName
ClassMethods
@end
In order to implement the methods we declared in the @interface
section, therefore, we need to write the following code:
@implementation BankAccount
-(void) setAccount: (long) y andBalance: (double) x;
{
accountBalance = x;
accountNumber = y;
}
29. Declaring and Initializing a Class
Instance
so far all we have done is define the blueprint for our class. In
order to do anything with this class, we need to create
instances of it.
The first step in this process is to declare a variable to store a
pointer to the instance when it is created. We do this as
follows:
BankAccount *account1;
Having created a variable to store a reference to the class
instance, we can now allocate memory in preparation for
initializing the class:
account1 = [BankAccount alloc];
30. Automatic Reference Counting
(ARC)
In the first step of the previous section we allocated memory for
the creation of the class instance.
In releases of the iOS SDK prior to iOS 5, good programming
convention would have dictated that memory allocated to a
class instance be released when the instance is no longer
required.
Failure to do so, in fact, would have resulted in memory leaks
with the result that the application would continue to use up
system memory until it was terminated by the operating system.
31. Cont…
Objective-C has provided similar functionality on other
platforms but not for iOS.
That has now changed with the introduction of automatic
reference counting in the iOS 5 SDK and it is not necessary
to call the release method of an object when it is no longer
used in an application.
32. Cont..
the ARC avoids the necessity to call the release method
of an object it is still, however, recommended that any
strong outlet references be assigned nil in the
viewDidUnload methods of your view controllers to
improve memory usage efficiency. As a
result, examples in this book will follow this convention
where appropriate.
33. Calling Methods and Accessing
Instance Data
We have now created a new class called BankAccount.
Within this new class we declared some instance
variables to contain the bank account number and current
balance together with some instance methods used to
set, get and display these values.
In the preceding section we covered the steps necessary
to create and initialize an instance of our new class.
The next step is to learn how to call the instance methods
we built into our class.
34. Cont…
The syntax for invoking methods is to place the object pointer
variable name and method to be called in square brackets ([]).
For example, to call the displayAccountInfo method on the
instance of the class we created previously we would use the
following syntax:
[account1 displayAccountInfo];
35. Objective-C and Dot Notation
hose familiar with object oriented programming in Java, C++
or C# are probably reeling a little from the syntax used in
Objective-C.
They are probably thinking life was much easier when they
could just use something called dot notation to set and get
the values of instance variables.
The good news is that one of the features introduced into
version 2.0 of Objective-C is support for dot notation.
36. Cont…
Dot notation involves accessing an instance variable by
specifying a class instance followed by a dot followed in turn
by the name of the instance variable or property to be
accessed:
classinstance.property
double balance1 = account1.accountBalance;
37. How Variables are Stored
When we declare a variable in Objective-C and assign a
value to it we are essentially allocating a location in memory
where that value is stored.
Take, for example, the following variable declaration:
int myvar = 10;
38. An Overview of Indirection
Indirection involves working with pointers to the location of
variables and objects rather than the contents of those items.
In other words, instead of working with the value stored in a
variable, we work with a pointer to the memory address where
the variable is located.
Pointers are declared by prefixing the name with an asterisk
(*) character.
For example to declare a pointer to our myvar variable we
would write the following code:
int myvar = 10;
int *myptr;
39. Cont..
he address of a variable is referenced by prefixing it with the
ampersand (&) character. We can, therefore, extend our
example to assign the address of the myvar variable to the
myptr variable:
int myvar = 10;
int *myptr;
40. Indirection and Objects
So far in this chapter we have used indirection with a
variable. The same concept applies for objects. In previous
chapters we worked with our BankAccount class. When doing
so we wrote statements similar to the following:
BankAccount *account1;
BankAccount *account1 = [[BankAccount alloc]
init];
41. Indirection and Object Copying
Due to the fact that references to objects utilize indirection it is
important to understand that when we use the assignment
operator (=) to assign one object to another we are not
actually creating a copy of the object.
Instead, we are creating a copy of the pointer to the object.
Consider, therefore, the following code:
BankAccount *account1;
BankAccount *account2;
BankAccount *account1 = [[BankAccount alloc]
init];
account2 = account1;
42. Creating the Program Section
The last stage in this exercise is to bring together all the
components we have created so that we can actually see the
concept working.
The last section we need to look at is called the program
section.
This is where we write the code to create the class instance
and call the instance methods.
Most Objective-C programs have a main() routine which is
the start point for the application. The following sample main
routine creates an instance of our class and calls the
methods we created:
43. EX…
Int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool =
[[NSAutoreleasePool alloc] init];
// Create a variable to point to our class instance
BankAccount *account1;
// Allocate memory for class instance
account1 = [BankAccount alloc];
// Initialize the instance
account1 = [account1 init];
// Set the account balance
[account1 setAccountBalance: 1500.53];
44. // Set the account number
[account1 setAccountNumber: 34543212];
// Call the method to display the values of
// the instance variables
[account1 displayAccountInfo];
// Set both account number and balance
[account1 setAccount: 4543455 andBalance:
3010.10];
// Output values using the getter methods
NSLog(@"Number = %i, Balance = %f",
[account1 getAccountNumber],
[account1 getAccountBalance]);
[pool drain];
return 0;}
47. If you do not see this window, simply select the Window ->
Welcome to Xcode menu option to display it.
From within this window click on the option to Create a new
Xcode project. This will display the main Xcode 4 project
window together with the New Project panel where we are able
to select a template matching the type of project we want to
develop:
48.
49. Begin by making sure that the Application option located
beneath iOS is selected.
The main panel contains a list of templates available to
use as the basis for an application.
The options available are as follows:
Master-Detail Application
Used to create a list based application. Selecting an item
from a master list displays a detail view corresponding to
the selection.
The template then provides a Back button to return to the
list.
You may have seen a similar technique used for news
based applications, whereby selecting an item from a list
of headlines displays the content of the corresponding
news article.
When used for an iPad based application this template
implements a basic split-view configuration.
50. Cont..
OpenGL Game
As discussed in iOS 5 Architecture and SDK
Frameworks, the OpenGL ES framework provides an
API for developing advanced graphics drawing and
animation capabilities.
The OpenGL ES Game template creates a basic
application containing an OpenGL ES view upon which
to draw and manipulate graphics and a timer object.
51. Cont..
Page-based Application
Creates a template project using the page view
controller designed to allow views to be transitioned by
turning pages on the screen.
Tabbed Application
Creates a template application with a tab bar.
The tab bar typically appears across the bottom of the
device display and can be programmed to contain items
that, when selected, change the main display to different
views.
52. Cont…
Utility Application
Creates a template consisting of a two sided view.
For an example of a utility application in action, load
up the standard iPhone weather application.
Pressing the blue info button flips the view to the
configuration page.
Single View Application
Creates a basic template for an application
containing a single view and corresponding view
controller.
Empty Application
The most basic of templates this creates only a
window and a delegate.
57. Changing Component
Properties
◦ With the property panel for the View selected in the main
panel, we will begin our design work by changing the
background color of this view.
◦ Begin by making sure the View is selected and that the
Attribute Inspector (View -> Utilities -> Show Attribute
Inspector) is displayed in the right hand panel.
◦ Click on the gray rectangle next to the Background label to
invoke the Colors dialog.
◦ Using the color selection tool, choose a visually pleasing
color and close the dialog. You will now notice that the view
window has changed from gray to the new color selection.
58. Adding Objects to the User
Interface
The next step is to add a Label object to our view.
To achieve this, select Cocoa Touch -> Controls from the
library panel menu, click on the Label object and drag it to the
center of the view.
Once it is in position release the mouse button to drop it at that
location:
60. double click on the text in the label that currently reads
“Label” and type in “Hello World”. At this point, your View
window will hopefully appear as outlined in Figure
(allowing, of course, for differences in your color and font
choices):