Objective-C Foundation Lecture 2 1 Introduction to Objective-C Objective-C is the official programming language used to develop iPhone applications Object-Oriented Language 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 2 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 3 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 4 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) Example: Bullet Class We use an example to show how to declare and define a class Example: Bullet 5 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 6 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 7 Class Declaration (.h File) Line 4 defines the class name “Bullet” “: NS Object” is about inheritance – ignore it by now 8 Class Declaration (.h File) Lines 5 – 7 declare the list of member variables Use “float” because of sub-pixel rendering in iphone app. 9 Class Declaration (.h File) Lines 10 – 12 are needed to get and set the variables of an object of Bullet class from other objects 10 Class Declaration (.h File) Lines 14 – 16 define the two methods (messages) supported by this class 11 Class Definition (.m File) Line 1 imports the declaration file (.h) 12 Class Definition (.m File) Line 3 is the standard implementation syntax 13 Class Definition (.m File) Line 4 directly corresponds to the three @property statements in lines 10 – 12 of the .h file 14 Class Definition (.m File) Line 6 – 12 contain implementation of the first method initialialze which takes 3 parameters 15 Class Definition (.m File) Lines 14 – 17 contain implementation of the second method move which takes 2 parameters 16 Class Definition (.m File) Lines 19 – 21 must be included in all classes – related to object de-allocation 17 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; } 18 Class Method vs. Instance Method Class Method 19 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 20 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: 21 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 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 22 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: 23 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: 24 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: 25 delete 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: 26 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: 27 Carson age 29, Carson gpa 3.4 Objective-C Array To make an array holding elements of intrinsic variable type (e.g. int) 28 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 29 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 30 Objective-C Array: NSMutableArray By using NSMutableArray, we can dynamically modify the array elements by using the method addObject 31 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 32 [array release]; A Summary 33 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]; 34 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" 35