Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objective-C Foundation Lecture 2 1. Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object.

Similar presentations


Presentation on theme: "Objective-C Foundation Lecture 2 1. Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object."— Presentation transcript:

1 Objective-C Foundation Lecture 2 1

2 Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object  User-Defined Class  Variables Declaration and Initialization  Methods Declaration and Invocation  Objective-C String and Array  During Lab  Programmatically Creating and Managing UI Objects  Common properties of UI components  Animation – NSTimer  Removal of UI Objects 2

3 Introduction to Objective-C  Objective-C is the official programming language used for developing iPhone apps  Objective-C is the superset of C  Just like the case of C/C++  Everything that works in C also works in Objective-C  Implication:  You can use a C programming style to develop iPhone apps, although it is not formal 3

4 4 Intrinsic Variable Types  Intrinsic variable types we use in C/C++ also work in Objective-C  Below are some of the supported intrinsic variables types 4 Intrinsic TypeDescriptionExample intIntegerint score = 2; floatSingle precision floating point number float timeElapsed = 1.0f; BOOL bool Boolean variableBOOL isCollide = YES; bool isCollide = true;

5 5 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 } 5

6 6 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 } 6

7 7 Class vs. Object  A class is a template / prototype of certain kind of objects  Basically, it is a type (compared 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

8 Class vs. Object Conceptual Example – Room and CYC603  Class  Room  Members  Light (is on or off)  No. of Chairs  No. of Tables  Projector status (on or off)  No. of Computers  Methods  Move in/Out Chairs/Tables/Computers  Turn on/off the light  Turn on/off the projector 8  Object  CYC103 EEE Computer Lab (An instance of Room Class)  Members  Light = on  No. of Chairs = 40+  No. of Tables = 10+  Projector = on  No. of Computers = 10+

9 9 Objective-C Class Example – GUI- Specific Variable Types  We need GUI-specific variable type (class) for displaying the UI components on the screen when creating a GUI application  Below are all those we are using in the project Image-Specific Type (Class) Description UIImageViewProvides a view-based container for displaying a single image UILabelImplements a read-only text box on the view

10  For example, in a GUI application, a given image view on the screen is an object (e.g. the image, i.e., life1Image)  It belongs to class UIImageView  It has its state: The image is currently hidden or not  It has its behaviour: When receiving a method call (say, telling it to change the hidden status), it will respond to the caller by changing its own hidden status  e.g., life1Image.hidden = YES  life1Image.hidden = No 10 Objective-C Object Example I – life1Image

11 11 Objective-C Object Example II – scoreLabel  For example, in a GUI application, a given text label on the screen is an object (e.g., the “score” 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 User-Defined Class  In this project, what we are doing is implementing the class – VolcanoRockEscapingViewController  As practised in previous lab session, we have to: 1. In header file (.h file) 1. Variables Declaration and Initialization 2. Methods Declaration 2. In Implementation file (.m file) 1. Corresponding methods implementation 12

13 Variables Declaration and Initialization 1. Intrinsic type declaration and initialization, e.g., 1. int score = 0; 2. float timeElapsed = 0.0f; 2. Class type declaration; 1. UILabel * scoreLabel = [UILabel alloc]; 2. VolcanoRock * volcanoRock = [VolcanoRock alloc]; (VolcanoRock is another user-defined class that you will use later) “*” is known as pointer, which points to the memory location storing the newly created object (in objective-C, a new object is created by calling alloc). 13

14 Methods Declaration  No Return Variable:  - (void) initializeData;  Has Return Variable  - (id) initializeVolcanoRock;  - (bool) isOutOfBoundary;  Has one input parameter;  - (void) initializeData : (int) variable1; 14

15 Methods Implementation  Each method should be implemented in between @implementation and @end pair  In implementing a method, we have to implement the codes in- between the braces after the method declaration - (void) initializeData { // Implement some codes here } 15

16 Methods Invocation  Within a method implementation, you may need to invoke another method. This is done by“[ ]”.  Method invocation of the same object (e.g, invoke “initializeData” in “viewDidLoad” ) - (void) viewDidLoad { // Implement some codes here [self intializeData]; }  Method invocation of the other object (e.g., invoke “initializeVolcanoRock”of volcanoRock in “initializeData” - (void) initializeData { // Implement some codes here volcanoRock = [volcanoRock initializeVolcanoRock]: } 16

17 Methods Invocation  Method invocation with one input parameter. Parameters are separated by “:” [manImage setCenter: CGPointMake( DEFAULT_MANIMAGE_CENTER_X, DEFAULT_MANIMAGE_CENTER_Y)]; Note that manImage is an UIImageView object  We will discuss what CGPoint is later 17

18 18 Objective-C Variable Types  Similar to C++ or Java, Objective-C also has its own list of variable types.  Below are all those we are using in the project Objective-C Type (Class) Description NSStringHolding a sequence of characters. The characters inside are not expected to be modified. NSMutableStringSame as NSString except that the characters inside are expected to be modified. NSArrayHolding a list of objects, e.g., NSString variable, GUI- specific variables, user-defined variables. The objects inside are not expected to be modified. NSMutableArraySame as NSArray except that the objects inside can be modified.

19 19 Objective-C String 19  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

20 20 Objective-C String: NSString  Example: int age = 29; float score = 99.9; NSString * carsonStr = @"Carson"; NSString * string1 = [NSString stringWithFormat:@"%@ age %d, %@ score %.01f ", carsonStr, age, carsonStr, score]; // NSLog is to output string to the Console NSLog(string1);  The output on the console is:  Carson age 29, Carson score 99.9 20

21 21 C Style 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;

22  To make an array holding objects of a class (e.g., volcanoRock)  Create an array object of class NSMutableArray  Add the objects of the same class into the array object  Finding the size of the array is important when we want to traverse the whole array  We can do so by invoking the count method  e.g. [array count]; (return 3 in this case) 22 Objective-C Array 22 array object volcanoRock

23 23 Objective-C Array: NSMutableArray I  By using NSMutableArray, we can dynamically modify the array elements by using the method addObject  NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:1];  VolcanoRock * volcanoRock1 = [[VolcanoRock alloc] initializeRock];  VolcanoRock * volcanoRock2 = [[VolcanoRock alloc] initializeRock];  [array addObject:volcanoRock1];  [array addObject:volcanoRock2];

24 24 Objective-C Array: NSMutableArray II  To refer to a particular element in an array. You need to use the method objectAtIndex  VolcanoRock * volcanoRock1 = [array objectAtIndex:0];

25 25 Objective-C Array: NSMutableArray III  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]; 25

26 Summary of the Comparison Between C/C++ and Objective-C 26 C/C++Objective-C Framework inclusion#include #import Header File inclusion#include "Dog.h"#import "Dog.h" Constant Definition#define RATE 1.0 Header File/ Implementation FileC:.h/.c C++:.h/.cc.h/.m Member Variables Declarationint age; Class Method Declarationstatic void helloWorld();+ (void) helloWorld; Instance Method Declarationint getAge();- (int) getAge; Dynamic Memory Allocation and Pointer variable Assignment Dog * dog1=malloc(sizeof(Dog)); Dog * dog1 = new Dog; Dog * dog1 = [Dog alloc];

27 Summary of the Comparison Between C/C++ and Objective-C 27 C/C++Objective-C Class Method InvokeDog::getAge();[NSString stringWithFormat:@"%d", age]; Instance Method Invokedog1->getAge();[dog1 getAge]; String Format"Hello"@"Hello"

28 Common Updates on UI Components 28  Setting Text for UILabel Object  Tutorial 1 Last Section – scoreLabel, timeLabel  UI components usually contain a property known as hidden  e.g., component.hidden = YES implies that the UI component is invisible; setting it to NO make it visible  Tutorial 2 Section 2.1 – life1Image.hidden = YES  Changing the center position of UI components to a specified location on the screen view, e.g.,  [component setCenter:CGPointMake(center_x, center_y)];  Used in the VolcanoRock “move” method (Tutorial 2 Section 3.2) Center (center_x, center_y)

29 Create and Display an Image 1. Create a UIImageView variable and specify the image file it is displaying UIImageView *myImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@”pic.jpg”]]; 2. Specify the frame (size and location) [myImageView setFrame:CGRectMake(x, y, width, height)];(x, y, width, height) 3. Show it on the screen [self.view addSubview:myImageView]; 29

30 Example – Adding Man Image on to the screen (Tutorial 2 Section 2.2) 30  Create a UIImageView object with the image named “man.jpg”  Declare the variable somewhere:  UIImageView * manImage;  Initialize the variable: (Recall Objective-C type of initializaton)  manImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@“man.jpg"]];  Setting the boundary frame of the UIImageView object  [manImage setFrame:CGRectMake(DEFAULT_MAN_IMAGE_ORIGIN_X, DEFAULT_MAN_IMAGE_ORIGIN_Y, DEFAULT_MAN_IMAGE_WIDTH, DEFAULT_MAN_IMAGE_HEIGHT)];  Putting the UIImageView object to the view to display  [self.view addSubview:manImage];

31 Screen View Layer Concept 31  The device has to follow a certain sequence order in drawing the view objects on the screen view.  Usually, the drawing order is following the order of adding the object to the view  For example,  object A is added to self.view (i.e., [self.view addSubview:objectA])  Then, object B is added to self.view  Both object A and object B overlap in some places  In this case, object B will be on top of object A object A object B

32 Initial Position of VolcanoRock (Tutorial 2 Section 2.3) 32 volcanoRock volcanoImage Very strange to have the volcanoRock to be shot out at the current location

33 Push VolcanoRock below VolcanoImage  Change the drawing order by: [self.view insertSubview:volcanoRock belowSubview:volcanoImage]; 33 VolcanoImage volcanoRock

34 Algorithms in Animation 34  Move the image object continuously within a short period of time to give the illusion of animation  Periodically invoke a method “progress”  How?  NSTimer can be used to perform this function  In the method “progress”  Generate New VolcanoRock (if necessary)  Method “initializeVolcanoRock”in VolcanoRock Class  Update the current position of the existing volcanoRock  Method “move”in VolcanoRock in VolcanoRock Class

35 NSTimer Class 35  Allows a certain method to be activated repeatedly within a predefined period of time.  The finest scale possible is : 1/30 second  To initialize NSTimer:  timer = nil;  Reset the Timer  timer=[NSTimer scheduledTimerWithTimeInterval:DEFAULT_TIMER_RATE  Schedule the timer to activate after DEFAULT_TIMER_RATE seconds target:self  The current view controller will handle the timer activation selector:@selector(progress)  The method progress will be invoked when timer is activated userInfo:nil repeats:YES];  The timer will be activated periodically

36 Moving Out of Boundary (Tutorial 2 Section 3.4) 36  VolcanoRock falls outside of the screen view boundary should be removed  Method “isOutOfBoundary”in VolcanoRock Class  We will discuss more on moving out of the screen view boundary next lecture

37 Removing an UI Object  To remove an UI object being referenced by VolcanoRock * volcanoRock from the screen: [volcanoRock removeFromSuperView];  To “release” the memory space occupied by the object referenced by volcanoRock: [volcanoRock release]; 37


Download ppt "Objective-C Foundation Lecture 2 1. Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object."

Similar presentations


Ads by Google