Objective-C Foundation Lecture 2 1 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 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 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 4 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 Objective-C Type int unsigned float double char BOOL 5 Description Example Integer int anInteger = -10; Unsigned integer unsigned anInteger = 50; Single precision float myFloat = -0.333; floating point number Double precision double myDouble = floating point number 0.33827382732234; Character char myCharacter = ‘s’; Boolean variable BOOL isHappy = 0; 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 project Image-Specific Type (Class) UIImageView 6 Description 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) 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 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 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 9 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” 10 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) 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 11 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 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 12 Example: Bullet Class We use an example to show how to declare and define a class Example: Bullet 13 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 bullet e.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 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 14 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 Class Declaration (.h File) Lines 1 – 2 are library and header file import statements #import works like the C/C++ #include statement 15 Class Declaration (.h File) Line 4 defines the class name “Bullet” “: NS Object” is about inheritance – ignore it by now 16 Class Declaration (.h File) Lines 5 – 7 declare the list of member variables Use “float” because of sub-pixel rendering in iphone app. 17 Class Declaration (.h File) Lines 10 – 12 are needed to get and set the variables of an object of Bullet class from other objects 18 Class Declaration (.h File) Lines 14 – 16 define the two methods (messages) supported by this class 19 Class Definition (.m File) Line 1 imports the declaration file (.h) 20 Class Definition (.m File) Line 3 is the standard implementation syntax 21 Class Definition (.m File) Line 4 directly corresponds to the three @property statements in lines 10 – 12 of the .h file 22 Class Definition (.m File) Line 6 – 12 contain implementation of the first method initialialze which takes 3 parameters 23 Class Definition (.m File) Lines 14 – 17 contain implementation of the second method move which takes 2 parameters 24 Class Definition (.m File) Lines 19 – 21 must be included in all classes – related to object de-allocation 25 Syntax of Methods Method that takes parameters - (void) move: (float) moveX: (float) moveY { // Do something here Parameter } Return type of method Instance method: - (type) name Method name Class method: + Method that takes no parameters - (int) getValue { // Do something here return anInt; } 26 Class Method vs. Instance Method Class Method 27 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 Class Method vs. Instance Method Instance method 28 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 Example: Bullet Class (Continued) We now need to know how to make use of the Bullet class, specifically: 29 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 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: 30 Bullet Class: Create and Initialize Object OR 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 31 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: 32 bullet->move(moveX, moveY); Bullet Class: Get and Set Variables Getting and setting a variable from outside Bullet.m can only be done when: Getting a member variable of a bullet object: @property statement for that variable is defined in .h file @synthesize statement for that variable is defined in .m file e.g. float x = bullet.centerX; e.g. float rad = bullet.radius; Setting a member variable of a bullet object: 33 e.g. bullet.centerX = 10.0; e.g. bullet.centerY = 30.0; 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: 34 delete bullet; 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 35 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: 2. Allocating an object with initial values, and pointing to that object: Bullet * bullet; bullet = [[Bullet alloc] initialize: 10.0: 10.0: 5.0]; Combining 1 and 2 as a single statement; 36 Bullet * bullet = [[Bullet alloc] initialize: 10.0: 10.0: 5.0]; Pointer Example Memory (heap space) 37 Pointer Example Memory (heap space) bulletA bulletB 38 Pointer Example Memory (heap space) bulletA bulletB 39 centerX = 5.0; centerY = 10.0; radius = 15.0; Pointer Example Memory (heap space) bulletA bulletB 40 centerX = 5.0; centerY = 10.0; radius = 15.0; centerX = 6.0; centerY = 12.0; radius = 18.0; Pointer Example Memory (heap space) bulletA bulletB 41 centerX = 7.0; centerY = 13.0; radius = 15.0; centerX = 6.0; centerY = 12.0; radius = 18.0; Pointer Example Memory (heap space) bulletA bulletB 42 centerX = 6.0; centerY = 12.0; radius = 18.0; Pointer Example Memory (heap space) bulletA bulletB 43 Pointer Example – Memory Leak Memory (heap space) bulletA bulletB 44 centerX = 7.0; centerY = 13.0; radius = 15.0; centerX = 6.0; centerY = 12.0; radius = 18.0; Pointer Example – Memory Leak Memory (heap space) bulletA bulletB Memory leak occurs: This object can no longer be accessed but is kept in memory 45 centerX = 7.0; centerY = 13.0; radius = 15.0; centerX = 6.0; centerY = 12.0; radius = 18.0; Pointers – Memory Management We should remove the object when we do not need it in future 46 This avoids memory leaks Each alloc should be associated with a release Pointers – The “Self” Reserved Word Imagine there is a pointer called self which points to the object itself when an object is created self bullet 47 Memory (heap space) centerX = 5.0; centerY = 10.0; radius = 15.0; 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 Bullet.h should use the keyword “self” as the subject Bullet.m 48 Member variables Parameters Pointers – The “Self” Reserved Word Sometimes, we even need it to call on or return the object itself Bullet.m The purpose is to make this call valid 49 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 Objective-C String Strings in Objective-C are defined with an “@” sign There are two types of strings: NSString and NSMutableString e.g. @"Carson“ It differentiates Objective-C strings from C style strings 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: 50 e.g. NSString * carsonStr = @"Carson"; carsonStr is a pointer to an NSString object which is dynamically created 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 Console NSLog(string1); The output on the console is: 51 Carson age 29, Carson gpa 3.4 Objective-C Array To make an array holding elements of intrinsic variable type (e.g. int) 52 We can simply use C/C++ style of creating array Example: int myArray[100]; myArray[0] = 555; myArray[1] = 666; 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 array object centerX = 5.0; centerY = 10.0; radius = 15.0; centerX = 6.0; centerY = 12.0; radius = 18.0; bullet objects ... Finding the size of it is important when we want to traverse the whole array 53 We can do so by invoking the count method e.g. [array count]; 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] = red array[1] = white array[2] = blue 54 Objective-C Array: NSMutableArray By using NSMutableArray, we can dynamically modify the array elements by using the method addObject 55 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 56 [array release]; A Summary 57 Comparison between C/C++ and ObjectiveC 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]; 58 Comparison between C/C++ and Objective-C C/C++ Objective-C Class Method Invoke Dog::getAge(); [Dog getAge]; Instance Method Invoke dog1->getAge(); [dog1 getAge]; String Format "Hello" @"Hello" 59