Objective C Tutorial
Objective C Tutorial
TUTORIAL
BASIC OBJECTIVE-C
OBJECTIVE-C HOME
Objective-C is a general-purpose, objectoriented programming language that adds
Smalltalk-style
messaging
to
the
C
programming language.
This is the main programming language
used by Apple for the OS X and iOS
operating systems and their respective
APIs, Cocoa and Cocoa Touch.
LECTURER: NGUYEN MINH DAO
OBJECTIVE-C OVERVIEW
Object-Oriented Programming
Fully supports object-oriented programming,
including the four pillars of object-oriented
development:
Encapsulation
Data hiding
Inheritance
Polymorphism
LECTURER: NGUYEN MINH DAO
OBJECTIVE-C OVERVIEW
(2)
Foundation Framework
Foundation Framework provides
features and they are listed below.
large
set
of
OBJECTIVE-C OVERVIEW
(3)
Learning Objective-C
The most important thing to do when learning
Objective-C is to focus on concepts and not get lost
in language technical details.
The purpose of learning a programming language is
to become a better programmer; that is, to become
more effective at designing and implementing new
systems and at maintaining old ones.
LECTURER: NGUYEN MINH DAO
OBJECTIVE-C OVERVIEW
(4)
Use of Objective-C
Objective-C, as mentioned earlier, is used in iOS
and Mac OS X.
It has large base of iOS users and largely increasing
Mac OS X users.
And since Apple focuses on quality first and its
wonderful for those who started learning ObjectiveC.
LECTURER: NGUYEN MINH DAO
OBJECTIVE-C
ENVIRONMENT SETUP
Xcode8
Xcode 8 includes everything you need to create amazing
apps for iPhone, iPad, Mac, Apple Watch, and Apple TV.
This radically faster version of the IDE features new editor
extensions that you can use to completely customize your
coding experience.
New runtime issues alert you to hidden bugs by pointing out
memory leaks, and a new Memory Debugger dives deep into
your object graph.
Swift 3 includes more natural and consistent API naming,
which you can experiment with in the new SwiftLECTURER:
Playgrounds
NGUYEN MINH DAO
10
11
OBJECTIVE-C PROGRAM
STRUCTURE
Objective-C Hello World Example
A Objective-C program basically consists of the following
parts:
Preprocessor Commands
Interface
Implementation
Method
Variables
Statements & Expressions
Comments
LECTURER: NGUYEN MINH DAO
12
13
OBJECTIVE-C PROGRAM
STRUCTURE (2)
Let us look various parts of the above program:
1. The first line of the program#import <Foundation/Foundation.h>is
a preprocessor command, which tells a Objective-C compiler to include
Foundation.h file before going to actual compilation.
2. The next line@interface SampleClass:NSObjectshows how to create
an interface. It inherits NSObject, which is the base class of all objects.
3. The next line- (void)sampleMethod;shows how to declare a method.
4. The next line@endmarks the end of an interface.
5. The next line@implementation SampleClassshows
implement the interface SampleClass.
how
to
14
OBJECTIVE-C PROGRAM
STRUCTURE (3)
Let us look various parts of the above program:
6. The
next
line(void)sampleMethod{}shows
the
implementation of the sampleMethod.
7. The next line@endmarks the end of an implementation.
8. The next lineint main()is the main function where program
execution begins.
9. The next line /*...*/ will be ignored by the compiler and it has
been put to add additional comments in the program. So such
lines are called comments in the program.
10.The next lineNSLog(...)is another function available in
Objective-C which causes the message "Hello, World!" to be
displayed on the screen.
LECTURER: NGUYEN MINH DAO
15
16
OBJECTIVE-C BASIC
SYNTAX
Tokens in Objective-C
A
Objective-C
program
consists of various tokens and
a token is either a keyword,
an identifier, a constant, a
string literal, or a symbol.
For example, the following
Objective-C
statement
consists of six tokens:
LECTURER: NGUYEN MINH DAO
17
OBJECTIVE-C BASIC
SYNTAX(2)
Semicolons ;
In Objective-C program, the semicolon is a statement
terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.
For example, following are two different statements:
18
OBJECTIVE-C BASIC
SYNTAX(3)
Comments
Comments are like helping text in your Objective-C
program and they are ignored by the compiler. They
start with /* and terminate with the characters */ as
shown below:
19
OBJECTIVE-C BASIC
SYNTAX(3)
Identifiers
An Objective-C identifier is a name used to identify a variable,
function, or any other user-defined item. An identifier starts
with a letter A to Z or a to z or an underscore _ followed by
zero or more letters, underscores, and digits (0 to 9).
Objective-C does not allow punctuation characters such as
@, $, and % within identifiers. Objective-C is acasesensitiveprogramming language.
Thus,Manpowerandmanpowerare two different identifiers
in Objective-C.
LECTURER: NGUYEN MINH DAO
20
OBJECTIVE-C BASIC
SYNTAX(4)
Keywords
The following list shows few
of the reserved words in
Objective-C.
These reserved words may
not be used as constant or
variable
or
any
other
identifier names.
21
OBJECTIVE-C BASIC
SYNTAX(5)
Whitespace in Objective-C
A line containing only whitespace, possibly with a comment,
is known as a blank line, and an Objective-C compiler
totally ignores it.
Whitespace is the term used in Objective-C to describe
blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables
the compiler to identify where one element in a statement,
such as int, ends and the next element begins.
LECTURER: NGUYEN MINH DAO
22
23
OBJECTIVE-C DATA
TYPES(2)
The array types and structure types are referred to
collectively as the aggregate types.
The type of a function specifies the type of the
function's return value. We will see basic types in the
following section whereas other types will be
covered in the upcoming chapters.
24
OBJECTIVE-C DATA
TYPES(3)
Integer Types
Following table gives you details
about standard integer types with
its storage sizes and value ranges:
To get the exact size of a type or a
variable on a particular platform,
you can use thesizeofoperator.
The expressionsizeof(type)yields
the storage size of the object or
type in bytes.
25
26
OBJECTIVE-C DATA
TYPES(4)
Floating-Point Types
Following table gives you details about standard
float-point types with storage sizes and value ranges
and their precision:
27
28
OBJECTIVE-C DATA
TYPES(5)
The void Type
The void type specifies that no value is available. It
is used in three kinds of situations:
29
OBJECTIVE-C VARIABLES
A variable is nothing but a name given to a storage area
that our programs can manipulate. Each variable in
Objective-C has a specific type, which determines the size
and layout of the variable's memory; the range of values
that can be stored within that memory; and the set of
operations that can be applied to the variable.
The name of a variable can be composed of letters, digits,
and the underscore character. It must begin with
either a letter or an underscore. Upper and lowercase
letters are distinct because Objective-C is case-sensitive.
LECTURER: NGUYEN MINH DAO
30
OBJECTIVE-C
VARIABLES(2)
Based on the basic types explained in previous chapter, there
will be the following basic variable types:
31
OBJECTIVE-C
VARIABLES(3)
Variable Definition in Objective-C:
A variable definition means to tell the compiler where and how much to
create the storage for the variable. A variable definition specifies a data type
and contains a list of one or more variables of that type as follows:
32
OBJECTIVE-C
VARIABLES(4)
Variable Definition in Objective-C:
Variables can be initialized (assigned an initial value)
in their declaration. The initializer consists of an
equal sign followed by a constant expression as
follows:
33
OBJECTIVE-C
VARIABLES(5)
Variable Definition in Objective-C:
For definition without an initializer: variables with static storage
duration are implicitly initialized with NULL (all bytes have the value
0); the initial value of all other variables is undefined.
A variable declaration is useful when you are using multiple files
and you define your variable in one of the files, which will be
available at the time of linking of the program. You will
useexternkeyword to declare a variable at any place. Though you
can declare a variable multiple times in your Objective-C program
but it can be defined only once in a file, a function or a block of
code.
LECTURER: NGUYEN MINH DAO
34
35
OBJECTIVE-C
VARIABLES(6)
Same concept applies on function declaration where you
provide a function name at the time of its declaration and its
actual definition can be given anywhere else. In the following
example, it's explained using C function and as you know
Objective-C supports C style functions also:
36
OBJECTIVE-C
VARIABLES(7)
Lvalues and Rvalues in Objective-C:
There are two kinds of expressions in Objective-C:
lvalue :Expressions that refer to a memory location is
called "lvalue" expression. An lvalue may appear as either
the left-hand or right-hand side of an assignment.
rvalue :The term rvalue refers to a data value that is stored
at some address in memory. An rvalue is an expression that
cannot have a value assigned to it which means an rvalue
may appear on the right- but not left-hand side of an
assignment.
LECTURER: NGUYEN MINH DAO
37
OBJECTIVE-C
VARIABLES(8)
Variables are lvalues and so may appear on
the left-hand side of an assignment. Numeric
literals are rvalues and so may not be
assigned and can not appear on the left-hand
side. Following is a valid statement:
38
OBJECTIVE-C CONSTANTS
The constants refer to fixed values that the program
may not alter during its execution. These fixed
values are also calledliterals.
Constants can be of any of the basic data types
likean integer constant, a floating constant, a
character constant, or a string literal. There are also
enumeration constants as well.
Theconstantsare treated just like regular variables
except that their values cannot be modified after
their definition.
LECTURER: NGUYEN MINH DAO
39
OBJECTIVE-C
CONSTANTS(2)
Integer literals
An integer literal can be a decimal, octal, or
hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and
nothing for decimal.
An integer literal can also have a suffix that is a
combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or
lowercase and can be in any order.
LECTURER: NGUYEN MINH DAO
40
OBJECTIVE-C
CONSTANTS(3)
Here are some examples of integer literals:
41
OBJECTIVE-C
CONSTANTS(4)
Floating-point literals
A floating-point literal has an integer part, a decimal
point, a fractional part, and an exponent part. You
can represent floating point literals either in decimal
form or exponential form.
While representing using decimal form, you must
include the decimal point, the exponent, or both and
while representing using exponential form, you must
include the integer part, the fractional part, or both.
The signed exponent is introduced by e or E.
LECTURER: NGUYEN MINH DAO
42
OBJECTIVE-C
CONSTANTS(5)
Floating-point literals
Here are some examples of floating-point literals:
43
OBJECTIVE-C
CONSTANTS(6)
Character constants
Character literals are enclosed in single quotes e.g.,
'x' and can be stored in a simple variable
ofchartype.
A character literal can be a plain character (e.g., 'x'),
an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
There are certain characters in C when they are
proceeded by a backslash they will have special
LECTURER: NGUYEN MINH DAO
44
45
46
OBJECTIVE-C
CONSTANTS(7)
String literals
String literals or constants are enclosed in double
quotes "". A string contains characters that are
similar to character literals: plain characters, escape
sequences, and universal characters.
You can break a long line into multiple lines using
string
literals
and
separating
them
using
whitespaces.
Here are some examples of string literals.
47
OBJECTIVE-C
CONSTANTS(8)
Defining Constants
There are two simple ways in C to define constants:
Using#definepreprocessor.
Usingconstkeyword.
48
49
OBJECTIVE-C
CONSTANTS(9)
The const Keyword
You can useconstprefix to declare constants with a
specific type as follows:
50
51
OBJECTIVE-C OPERATORS
An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulations.
Objective-C language is rich in built-in operators and
provides following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
LECTURER: NGUYEN MINH DAO
52
OBJECTIVE-C
OPERATORS(2)
Arithmetic Operators
Following table shows all the
arithmetic
operators
supported by Objective-C
language.
Assume variableAholds 10
and
variableBholds
20,
then:
53
54
OBJECTIVE-C
OPERATORS(3)
Relational Operators
Following table shows all
the relational operators
supported by Objective-C
language.
Assume variableAholds
10 and variableBholds
20, then:
LECTURER: NGUYEN MINH DAO
55
56
OBJECTIVE-C
OPERATORS(4)
Logical Operators
Following table shows all the
logical operators supported
by Objective-C language.
Assume variableAholds 1
and variableBholds 0, then:
57
58
OBJECTIVE-C
OPERATORS(5)
Logical Operators
Following table shows all the logical operators supported by
Objective-C language. Assume variableAholds 1 and
variableBholds 0, then:
59
60
OBJECTIVE-C
OPERATORS(6)
Bitwise Operators
Bitwise operator works on bits and perform bit by bit
operation.
The truth tables for &, |, and ^ are as follows:
61
OBJECTIVE-C
OPERATORS(6)
Bitwise Operators
The Bitwise operators
supported by Objective-C
language are listed in the
following table.
Assume variable A holds
60 and variable B holds
13 then:
LECTURER: NGUYEN MINH DAO
62
63
OBJECTIVE-C
OPERATORS(7)
Assignment Operators
There are following
assignment operators
supported by Objective-C
language:
64
65
OBJECTIVE-C
OPERATORS(8)
Misc Operators sizeof & ternary
There are few other important operators
includingsizeofand? :supported by Objective-C Language.
66
OPERATORS
PRECEDENCE IN
OBJECTIVE-C
67
OBJECTIVE-C LOOPS
Programming
languages
provide
various
control
structures that allow for more
complicated execution paths.
A loop statement allows us to
execute a statement or group
of statements multiple times
and following is the general
form of a loop statement in
most of the programming
languages:
LECTURER: NGUYEN MINH DAO
68
OBJECTIVE-C LOOPS(2)
Objective-C programming language provides the
following types of loop to handle looping
requirements.
69
OBJECTIVE-C LOOPS(2-1)
while
loop
Objective-C
in
70
71
OBJECTIVE-C LOOPS(2-2)
for loop in Objective-C
72
73
OBJECTIVE-C LOOPS(2-3)
do...while loop in
Objective-C
74
75
nested loops in
Objective-C
76
77
OBJECTIVE-C LOOPS(3)
Loop Control Statements:
Loop control statements change execution from its normal
sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.
78
OBJECTIVE-C LOOPS(3)
break statement in Objective-C
79
80
OBJECTIVE-C LOOPS(3)
continue statement in Objective-C
81
82
OBJECTIVE-C LOOPS(4)
The Infinite Loop:
A loop becomes infinite loop if a
condition never becomes false.
Theforloop
is
traditionally
used for this purpose. Since
none of the three expressions
that form the for loop are
required, you can make an
endless loop by leaving the
conditional expression empty.
LECTURER: NGUYEN MINH DAO
83
OBJECTIVE-C DECISION
MAKING
Decision making structures
require that the programmer
specify one or more conditions
to be evaluated or tested by
the program, along with a
statement or statements to be
executed if the condition is
determined to be true, and
optionally, other statements to
be executed if the condition is
determined to be false.
LECTURER: NGUYEN MINH DAO
84
OBJECTIVE-C DECISION
MAKING
Objective-C
programming
language assumes anynonzeroandnon-null
values
astrue,
and
if
it
is
eitherzeroornull, then it is
assumed asfalse value.
Objective-C
programming
language provides following
types
of
decision
making
statements. Click the following
links to check their details:
LECTURER: NGUYEN MINH DAO
85
OBJECTIVE-C DECISION
MAKING
Objective-C - if statement
86
87
OBJECTIVE-C DECISION
MAKING
Objective-C ifelse statement
88
89
OBJECTIVE-C DECISION
MAKING
Objective-C ifelse if else statement
90
91
OBJECTIVE-C DECISION
MAKING
Objective-C nested if statement
92
93
OBJECTIVE-C DECISION
MAKING
Objective-C switch statement
94
OBJECTIVE-C DECISION
MAKING
Objective-C switch statement
95
96
OBJECTIVE-C DECISION
MAKING
Objective-C nested switch statement
97
98
OBJECTIVE-C DECISION
MAKING
The ? : Operator
99
OBJECTIVE-C FUNCTIONS
A function is a group of statements that together
perform a task. Every Objective-C program has one C
function, which ismain(), and all of the most trivial
programs can define additional functions.
You can divide up your code into separate functions.
How you divide up your code among different
functions is up to you, but logically the division
usually is so each function performs a specific task.
LECTURER: NGUYEN MINH DAO
100
OBJECTIVE-C FUNCTIONS
A functiondeclarationtells the compiler about a
function's name, return type, and parameters. A
functiondefinitionprovides the actual body of the function.
Basically in Objective-C, we call the function as method.
The Objective-C foundation framework provides numerous
built-in methods that your program can call. For example,
methodappendString()to append string to another string.
A method is known with various names like a function or a
sub-routine or a procedure, etc.
LECTURER: NGUYEN MINH DAO
101
OBJECTIVE-C FUNCTIONS
Defining a Method
The general form of a method definition in ObjectiveC programming language is as follows:
102
OBJECTIVE-C FUNCTIONS
A method definition in Objective-C programming
language consists of amethod headerand amethod
body. Here are all the parts of a method:
Return Type:A method may return a value. Thereturn_typeis
the data type of the value the function returns. Some methods
perform the desired operations without returning a value. In this
case, the return_type is the keywordvoid.
Method Name:This is the actual name of the method. The
method name and the parameter list together constitute the
method signature.
LECTURER: NGUYEN MINH DAO
103
OBJECTIVE-C FUNCTIONS
A method definition in Objective-C programming language
consists of amethod headerand amethod body. Here are all
the parts of a method:
Arguments:A argument is like a placeholder. When a function is
invoked, you pass a value to the argument. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the arguments of a method. Arguments are
optional; that is, a method may contain no argument.
Joining Argument:A joining argument is to make it easier to read and to
make it clear while calling it.
Method Body:The method body contains a collection of statements that
define what the method does.
LECTURER: NGUYEN MINH DAO
104
105
106
OBJECTIVE-C FUNCTIONS
Calling a method:
When a program calls a function, program control is
transferred to the called method. A called method performs
defined task, and when its return statement is executed or
when its function-ending closing brace is reached, it returns
program control back to the main program.
To call a method, you simply need to pass the required
parameters along with method name, and if method returns
a value, then you can store returned value.
LECTURER: NGUYEN MINH DAO
107
108
OBJECTIVE-C FUNCTIONS
Function Arguments:
If a function is to use arguments, it must declare
variables that accept the values of the arguments.
These
variables
are
called
theformal
parametersof the function.
The formal parameters behave like other local
variables inside the function and are created upon
entry into the function and destroyed upon exit.
LECTURER: NGUYEN MINH DAO
109
OBJECTIVE-C FUNCTIONS
Function Arguments:
While calling a function, there are two ways that
arguments can be passed to a function:
110
OBJECTIVE-C FUNCTIONS
Function call by value in Objective-C
Thecall by valuemethod of passing arguments to a
function copies the actual value of an argument into the
formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect
By default, Objective-C programming language usescall
by valuemethod to pass arguments. In general, this
means that code within a function cannot alter the
arguments used to call the function. on the argument.
LECTURER: NGUYEN MINH DAO
111
112
OBJECTIVE-C FUNCTIONS
Function call by reference in Objective-C
Thecall by referencemethod of passing arguments to a function
copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter
affect the passed argument.
To pass the value by reference, argument pointers are passed to the
functions just like any other value. So accordingly, you need to
declare the function parameters as pointer types as in the following
functionswap(), which exchanges the values of the two integer
variables pointed to by its arguments.
LECTURER: NGUYEN MINH DAO
113
OBJECTIVE-C FUNCTIONS
Function call by reference in Objective-C
114
115
OBJECTIVE-C BLOCKS
An Objective-C class defines an object that combines
data with related behavior. Sometimes, it makes sense
just to represent a single task or unit of behavior, rather
than a collection of methods.
Blocks are a language-level feature added to C,
Objective-C and C++ which allow you to create distinct
segments of code that can be passed around to methods
or functions as if they were values.
Blocks are Objective-C objects which means they can be
added to collections like NSArray or NSDictionary.
LECTURER: NGUYEN MINH DAO
116
OBJECTIVE-C BLOCKS
117
OBJECTIVE-C BLOCKS
Blocks Take Arguments and Return Values
Blocks can also take arguments and return values
just like methods and functions.
Here is a simple example to implement and invoke a
block with arguments and return values.
118
119
120
121