1 Objective-C Foundation Lecture 2 1. 2 Flow of Lecture 2  Objective-C Basics  Introduction to Objective-C  Intrinsic Variables and Image-Specific.

Slides:



Advertisements
Similar presentations
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Advertisements

Chapter 7: User-Defined Functions II
The Web Warrior Guide to Web Design Technologies
Introduction to Objective-C and Xcode (Part 1) FA 175 Intro to Mobile App Development.
Objective-C Foundation Lecture 2 1. Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object.
IPhone Development Crash Course By Dylan Harris
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Guide To UNIX Using Linux Third Edition
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
OBJECT ORIENTED PROGRAMMING IN C++ LECTURE
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Object Oriented Software Development
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Microsoft Visual C++.NET Chapter 61 Memory Management.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Chapter 6: User-Defined Functions
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
Object-Oriented Programming in C++
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
More Objective-C Details FA 172 Intro to Mobile App Development.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Reverse a String iPhone/iPad, iOS Development Tutorial.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Introduction to Objective-C and Xcode (Part 4) FA 175 Intro to Mobile App Development.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 10: Void Functions
Student Book An Introduction
Programmazione I a.a. 2017/2018.
Lecture 6 C++ Programming
User-Defined Functions
Object Oriented Programming COP3330 / CGS5409
Chapter 3 Introduction to Classes, Objects Methods and Strings
CIS16 Application Development Programming with Visual Basic
Data Structures & Algorithms
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 TypeDescriptionExample intIntegerint anInteger = -10; unsignedUnsigned integerunsigned anInteger = 50; floatSingle precision floating point number float myFloat = ; doubleDouble precision floating point number double myDouble = ; charCharacterchar myCharacter = ‘s’; BOOLBoolean variableBOOL 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 project Image-Specific Type (Class) Description UIImageViewProvides a view-based container for displaying a single image (e.g. The grey time bar) UILabelImplements a read-only text box on the view (e.g. The “Target Shot” label) UIButtonImplements 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 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

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 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 ]; 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 ]; 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: statement for that variable is defined in.h file 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 subject Bullet.h Bullet.m Member 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   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  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 NSString * string1 = [NSString age %d, gpa %f ", carsonStr, age, carsonStr, gpa]; // NSLog is to output string to the Console NSLog(string1);  The output on the console is:  Carson age 29, Carson gpa

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] = red array[1] = white array[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 #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];

59 C/C++Objective-C Class Method InvokeDog::getAge();[Dog getAge]; Instance Method Invokedog1->getAge();[dog1 getAge]; String Comparison between C/C++ and Objective-C