1 Objective-C Foundation Lecture 2 1. 2 Flow of Lecture 2 Objective-C Basics Introduction to...

Preview:

Citation preview

1

Objective-C Foundation

Lecture 2

1

2

Flow of Lecture 2 Objective-C Basics

Introduction to Objective-C Intrinsic Variables and Image-Specific Variables Execution Flow Control

Object-Oriented Programming in Objective-C Class and Object Example Codes for Defining and Using a Class

Objective-C Pointers Pointer and Memory Management Objective-C Type of String Objective-C Type of Array

3

Flow of Lecture 2 Objective-C Basics

Introduction to Objective-C Intrinsic Variables and Image-Specific Variables Execution Flow Control

Object-Oriented Programming in Objective-C Class and Object Example Codes for Defining and Using a Class

Objective-C Pointers Pointer and Memory Management Objective-C Type of String Objective-C Type of Array

4

Introduction to Objective-C Objective-C is the official programming

language used to develop iPhone applications

Objective-C is the superset of C Everything that works in C also works in

Objective-C Implication:

We can use a C style programming in developing iPhone app although it is not formal

5

Intrinsic Variable Types Intrinsic variable types we use in C/C++ also work in

Objective-C Below is some of the supported intrinsic variables

types

5

Objective-C Type

Description Example

int Integer int anInteger = -10;

unsigned Unsigned integer unsigned anInteger = 50;

float Single precision floating point number

float myFloat = -0.333;

double Double precision floating point number

double myDouble = 0.33827382732234;

char Character char myCharacter = ‘s’;

BOOL Boolean variable BOOL isHappy = 0;

6

Image-Specific Variable Types We need image-specific variable type (class) for

displaying the graphics on the screen when creating a GUI application

Below are all those we are using in the projectImage-Specific

Type (Class)

Description

UIImageView Provides a view-based container for displaying a single image (e.g. The grey time bar)

UILabel Implements a read-only text box on the view (e.g. The “Target Shot” label)

UIButton Implements a button on the touch screen that intercepts touch events(e.g. The “Shoot” button)

7

Flow Control – Conditional Statement Objective-C uses exactly the same syntax as

that of C/C++ in conditional statements Example:int a = 0;

int b = 1;

if (a < b){

// Do something here

} else{

// Do another thing here

}

7

8

Flow Control – Loop Control Objective-C uses exactly the same syntax as

that of C/C++ in for-loop and while-loop statements

For-loop example:for (int i = 0; i < b; i++){

// Do something here

} While-loop example;while (a < b){

// Do something here

}

8

9

Flow of Lecture 2 Objective-C Basics

Introduction to Objective-C Intrinsic Variables and Image-Specific Variables Execution Flow Control

Object-Oriented Programming in Objective-C Class and Object Example Codes for Defining and Using a Class

Objective-C Pointers Pointer and Memory Management Objective-C Type of String Objective-C Type of Array

10

Object-Oriented Programming (OOP) The programming style that you have learned

before is called procedural programming style Break down programming task into functions / sub-

routines The program composes of a sequence of function calls

Object-oriented programming introduces concept of “objects” Break down programming task into objects The program is modeled as interactions between

different objects by passing of messages (invoking the methods of the objects)

Each object has its own states (member variables) and behaviours (responses to method invocations)

11

Class vs. Object We need to define classes in program code

before creating and using objects A class is a template / prototype of certain kind

of objects Basically, it is a type (compare with int, float …) Defines the characteristics of objects that belong to

the class Defines the fields (member variables) that the

object has Defines the things that the object can do (methods)

An object is an instance of a class Each object has its own copy of its member variables Each object can respond to invocation of its methods Many objects can be created from the same class

12

Objective-C Object For example, in a GUI application, a given text

label on the screen is an object (e.g. the “Target Shot” label) It belongs to class UILabel It has its state:

The text shown on the label It has its behaviour:

When receiving a method call (say, telling it to change the text), it will respond to the caller by changing its own label

13

Example: Bullet Class We use an example to show how to declare and

define a class Example: Bullet

In our project, the bullets we see on the screen are modeled as objects

Each bullet has its own center position x, y, and radius

We can invoke method (send message) to operate on a bullete.g. Tell it to translate (move) for a certain amount of pixels

When a bullet receives the method call, it will translate itself according to the given parameters

14

Objective-C Files: .h and .m Bullet.h

The header file that contains the declaration of a class

Also contains declaration of member variables and methods of the class

We use the “#import” statement to include other .h files (e.g. Foundation.h)

Bullet.m Contains the definition (implementation) of the

methods of the corresponding class, manipulation of data and objects

We need to use the “#import” statement to include the Bullet.h file

15

Class Declaration (.h File)

Lines 1 – 2 are library and header file import statements #import works like the C/C++ #include statement

16

Line 4 defines the class name “Bullet” “: NS Object” is about inheritance – ignore it by now

Class Declaration (.h File)

17

Lines 5 – 7 declare the list of member variables Use “float” because of sub-pixel rendering in iphone app.

Class Declaration (.h File)

18

Lines 10 – 12 are needed to get and set the variables of an object of Bullet class from other objects

Class Declaration (.h File)

19

Lines 14 – 16 define the two methods (messages) supported by this class

Class Declaration (.h File)

20

Line 1 imports the declaration file (.h)

Class Definition (.m File)

21

Line 3 is the standard implementation syntax

Class Definition (.m File)

22

Line 4 directly corresponds to the three @property statements in lines 10 – 12 of the .h file

Class Definition (.m File)

23

Line 6 – 12 contain implementation of the first method initialialze which takes 3 parameters

Class Definition (.m File)

24

Lines 14 – 17 contain implementation of the second method move which takes 2 parameters

Class Definition (.m File)

25

Lines 19 – 21 must be included in all classes – related to object de-allocation

Class Definition (.m File)

26

Syntax of Methods Method that takes parameters- (void) move: (float) moveX: (float) moveY {

// Do something here

}

Method that takes no parameters- (int) getValue {

// Do something here

return anInt;

}

Instance method: -

Class method: +

Return type of method

Method name

Parameter (type) name

27

Class Method vs. Instance Method Class Method

A class method is static and associated with a class

Denoted by a “+” sign in method declaration e.g., in the Bullet class, we can add a method printClassName that prints the class name on the screen

Invoke class method by [Bullet printClassName]; (use the class name directly)

Since this method does not require association with a particular object, so printClassName should be a class method

27

28

Class Method vs. Instance Method Instance method

An instance method associates with an object Denoted by a “-” sign in method declaration e.g., we call the move method on a particular object by

//create an object called myBullet of type Bullet

[myBullet move: 10.0: 5.0]; (myBullet is an OBJECT, not the class name)

Since every object can move differently, so move should be an instance method

28

29

Example: Bullet Class (Continued) We now need to know how to make use of the

Bullet class, specifically: How to create an object of class Bullet during

runtime How to initialize the position and radius of the

object How to invoke method of (send message to) the

object How to get and set the member variables of the

object How to de-allocate the object to free up system

memory after use

30

Manipulation of Objects C/C++/Objective-C all have the main function as the

entry point of the program “main.m” for Objective-C Here, we assume the codes that manipulate objects are

placed in the main.m, like this:

31

Bullet Class: Create and Initialize Object

Object creation and initialization can be done altogether [Bullet alloc]; creates the object [ ... initialize<parameters>];

sets the initial values of the object centerX, centerY and radius are float variables already

defined Bullet * bullet = [ ... ]; assigned the object to

the variable bullet NOTE: Bullet is the name of the class; bullet is the

variable name of the object We should implement an initialization method for all

classes

OR

32

Bullet Class: Invoke Method (Send Message)

Calling a method [bullet ...]; is the variable name of the object [ ... move<parameters>];

calls the move method with parameters moveX, and moveY are float variables already defined If the move method accepts no parameters, then

simply write:[bullet move];

C++ equivalent: bullet->move(moveX, moveY);

33

Bullet Class: Get and Set Variables Getting and setting a variable from outside

Bullet.m can only be done when: @property statement for that variable is defined in

.h file @synthesize statement for that variable is defined

in .m file Getting a member variable of a bullet object:

e.g. float x = bullet.centerX; e.g. float rad = bullet.radius;

Setting a member variable of a bullet object: e.g. bullet.centerX = 10.0; e.g. bullet.centerY = 30.0;

34

Bullet Class: De-allocate Object

De-allocating the object Simply call [bullet release]; NOTE: We are not calling the dealloc method

implemented in the Bullet class This is because the program will automatically call it at

appropriate time to really de-allocate the object

C++ equivalent: delete bullet;

35

Flow of Lecture 2 Objective-C Basics

Introduction to Objective-C Intrinsic Variables and Image-Specific Variables Execution Flow Control

Object-Oriented Programming in Objective-C Class and Object Example Codes for Defining and Using a Class

Objective-C Pointers Pointer and Memory Management Objective-C Type of String Objective-C Type of Array

36

Pointers Objects are usually created dynamically during

runtime A pointer is used to store the memory address

that holds up the object (“points to” the object) 1. Declaring a pointer variable:

Bullet * bullet;

2. Allocating an object with initial values, and pointing to that object: bullet = [[Bullet alloc] initialize: 10.0: 10.0: 5.0];

Combining 1 and 2 as a single statement; Bullet * bullet = [[Bullet alloc] initialize: 10.0: 10.0: 5.0];

37

Pointer Example

Memory (heap space)

38

Pointer Example

Memory (heap space)

bulletA

bulletB

39

Pointer Example

Memory (heap space)

bulletA

bulletB

centerX = 5.0;centerY = 10.0;radius = 15.0;

40

Pointer Example

Memory (heap space)

bulletA

bulletB

centerX = 5.0;centerY = 10.0;radius = 15.0;

centerX = 6.0;centerY = 12.0;radius = 18.0;

41

Pointer Example

Memory (heap space)

bulletA

bulletB

centerX = 7.0;centerY = 13.0;radius = 15.0;

centerX = 6.0;centerY = 12.0;radius = 18.0;

42

Pointer Example

Memory (heap space)

bulletA

bulletB centerX = 6.0;centerY = 12.0;radius = 18.0;

43

Pointer Example

Memory (heap space)

bulletA

bulletB

44

Pointer Example – Memory Leak

centerX = 7.0;centerY = 13.0;radius = 15.0;

centerX = 6.0;centerY = 12.0;radius = 18.0;

Memory (heap space)

bulletA

bulletB

45

Pointer Example – Memory Leak

bulletA

bulletB

centerX = 7.0;centerY = 13.0;radius = 15.0;

centerX = 6.0;centerY = 12.0;radius = 18.0;Memory leak occurs:

This object can no longer be accessed but is kept in memory

Memory (heap space)

46

Pointers – Memory Management We should remove the object when we do not

need it in future This avoids memory leaks Each alloc should be associated with a release

47

Pointers – The “Self” Reserved Word

bullet

centerX = 5.0;centerY = 10.0;radius = 15.0;

Imagine there is a pointer called self which points to the object itself when an object is created

self Memory (heap space)

48

Pointers – The “Self” Reserved Word Sometimes, we need to refer to the method or

variable of the bullet object within a method implementation of the Bullet class We should use the keyword “self” as the

subjectBullet.h

Bullet.mMember variables Parameters

49

Pointers – The “Self” Reserved Word Sometimes, we even need it to call on or return the

object itself

The purpose is to make this call valid

The return type of the method initialize is a pointer The method returns a pointer to itself, which will be

pointed to by the pointer variable bullet

Bullet.m

50

Objective-C String

50

Strings in Objective-C are defined with an “@” sign e.g. @"Carson“ It differentiates Objective-C strings from C style strings

There are two types of strings: NSString and NSMutableString A string of type NSString cannot be modified once it is

created A string of type NSMutableString can be modified Here, we will cover NSString only

Refer to documentation for NSMutableString Creation of a string of class NSString:

e.g. NSString * carsonStr = @"Carson"; carsonStr is a pointer to an NSString object which is

dynamically created

51

Objective-C String: NSString Example:int age = 29; float gpa = 3.4;

NSString * carsonStr = @"Carson";

NSString * string1 = [NSString stringWithFormat:@"%@ age %d, %@ gpa %f ", carsonStr, age, carsonStr, gpa];

// NSLog is to output string to the ConsoleNSLog(string1);

The output on the console is: Carson age 29, Carson gpa 3.4

51

52

Objective-C Array To make an array holding elements of intrinsic

variable type (e.g. int) We can simply use C/C++ style of creating array Example: int myArray[100];myArray[0] = 555;myArray[1] = 666;

53

Objective-C Array To make an array holding objects of a class (e.g.

Bullet) Create an array object of class NSArray or NSMutableArray Add the objects of the same class into the array object

Finding the size of it is important when we want to traverse the whole array We can do so by invoking the count method e.g. [array count];

53

centerX = 5.0;centerY = 10.0;radius = 15.0;centerX = 6.0;centerY = 12.0;radius = 18.0;

array object

...

bullet objects

54

Objective-C Array: NSArray NSArray is static and cannot be changed at runtime

i.e., We have to define all the elements inside the array when we initialize the array by using the initWithObjects method

The array has to be terminated by “nil” We can get a particular element inside the array by invoking the objectAtIndex method

The output is:array[0] = redarray[1] = whitearray[2] = blue

55

Objective-C Array: NSMutableArray By using NSMutableArray, we can dynamically modify

the array elements by using the method addObject

56

Objective-C Array: NSMutableArray When a particular element inside the array is

no longer in use, we can remove the element from the array Release the memory held by an object in the array

[[array objectAtIndex:i] release]; Remove the element from the array

[array removeObjectAtIndex:i]; All elements beyond index i will then be moved

one position forward Remove the array object itself

[array release];

56

57

A Summary

58

Comparison between C/C++ and Objective-C

58

C/C++ Objective-C

Framework inclusion #include <stdio.h> #import <Foundation/Foundation.h>

Header File inclusion #include "Dog.h" #import "Dog.h"

Constant Definition #define RATE 1.0 #define RATE 1.0

Header File/ Implementation File

C: .h/.c C++: .h/.cc

.h/.m

Member Variables Declaration

int age; int age;

Class Method Declaration static void helloWorld(); + (void) helloWorld;

Instance Method Declaration int getAge(); - (int) getAge;

Dynamic Memory Allocation and Pointer variable Assignment

Dog * dog1=malloc(sizeof(Dog));Dog * dog1 = new Dog;

Dog * dog1 = [Dog alloc];

5959

C/C++ Objective-C

Class Method Invoke Dog::getAge(); [Dog getAge];

Instance Method Invoke dog1->getAge(); [dog1 getAge];

String Format "Hello" @"Hello"

Comparison between C/C++ and Objective-C