1.89k likes | 1.92k Views
Programming in Objective-C. 涂昆源 副教授 萬能科技大學 資訊工程系. Part I The Objective-C 2.0 Language. Contents. Programming in Objective-C Classes, Objects, and Methods Data Types and Expressions Program Looping Making Decisions More on Classes Inheritance
E N D
Programming in Objective-C 涂昆源 副教授 萬能科技大學 資訊工程系
Contents • Programming in Objective-C • Classes, Objects, and Methods • Data Types and Expressions • Program Looping • Making Decisions • More on Classes • Inheritance • Polymorphism, Dynamic Typing, and Dynamic Binding • More on Variables and Data Types • Categories and Protocols • The Preprocessor • Underlying C Language Features
Getting Started in Objective-C • What Is Objective-C? • Your First Program • Steps for Using Xcode • Working with Variables
What is Objective-C • An object-oriented programming language (OOP) • Designed by Brad Cox (early 1980s) • Based on SmallTalk • Layered on the C language (1970s) • Licensed by NeXT Software (1988)
What is Objective-C (cont’d)? • Apple Acquired NeXT Software (1996) • NEXTSTEP environment was basis for Mac OS X • Objective-C became the standard development language for apps written for Mac OS X and then later of the iPod Touch, iPhone and iPad.
Your First Program // First program example #import <Foundation/Foundation.h> int main(int argc, constchar * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Programming is fun."); } return0; } Program 2.1
Steps For Using Xcode • Start the Xcode application. • If this is a new project, select File, New, NewProject... or choose CreateaNew XcodeProject from the startup screen. • For the type of application, select Mac OS X Application CommandLineTool, and click Next. • Select a name for your application and set its Type to Foundation. Click Next. • Select a name for your project folder, and a directory to store your project files in. Click Save. • In the left pane, you will see the file main.m. Highlight that file. Type your program into the edit window that appears in the rightmost pane.
Steps For Using Xcode • In the toolbar, select the middle icon under View. This will reveal the Debug area. That’s where you’ll see your output. • Build and run your application by clicking the Run button in the toolbar or selecting Run from the Product menu. • If you get any compiler errors or the output is not what you expected, make your changes to the program and rerun it.
Another Example Program 2.5
Exercises 1. What output would you expect from the following program?
Exercises 2. Identify the syntactic errors in the following program. Then type in and run the corrected program to make sure you have identified all the mistakes:
Exercises 3. What output would you expect from the following program?
Classes, Objects, and Methods • What Is a Class, Object, or Method? • Writing a Class to Work with Fractions • Accessing Instance Variables • Working with Multiple Objects
What’s an Object? • An object is a thing • OOP is dealing with objects • Everyday example of an object: A car
What’s an Object? • Things you do with your car • Drive it • Fill it with gas • Wash it • Get it serviced
What’s an Instance? • An object comes from a class (e.g. Cars) • A unique occurrence of an object from a class is called an instance • Your car may be red, have 20” wheels, and a V8 engine. Its VIN number uniquely identifies it
What’s a Method? • The action you perform on an object or on a class In Objective-C, the syntax is: [ClassorInstancemethod]; or [receivermessage];
Instances and Messages • First, create an new instance from a class: myCar = [Car new]; • Next, you perform actions with that instance: [myCar wash]; [myCar drive]; [myCar service]; [myCar topDown]; //my convertible!
Same Method, Different Objects You can use the same methods with other instances from the same calss: [suesCar wash]; [suesCar drive]; [suesCar service];
Translation Objects you work with will be a little different: [myWindow erase]; [myRect area]; [favorites showSongs]; [phoneNumber call]; Program 3.1
Accessing Instance Variables • Instance methods can access their own instance variables • Class methods can’t • They’re hidden from everyone else (data encapsulation)
Return Values • –(int) retrieveNumerator; Instance method called retrieveNumerator returns an integer value • –(double) retrieveDoubleValue; A instance method that returns a double precision value. • –(void) print; This method returns no value.
Method Arguments • Both instance methods from Program 3.2 –(void) setNumerator: (int) n; –(void) setDenominator: (int) d; • Both return no value. Each method takes an integer argument. • Method declaration Program 3.2
@interface Section • When defining a new class, you have to do a few things. • name its parentclass. • tell the Objective-C compiler where the class came from. • describe the data that members (instancevariables) of the class will contain. • specify what type of data is to be stored in the objects of this class. • define the type of operations, or methods • By convention, class names begin with an uppercase letter
@implementation Section • The section contains the actual code for the methods declared in the @interface section. • @interface section- declare methods. • @implementation section-define the methods (that is, give the actual code). • The general format for the section
Program Section • The section contains the code to solve your particular problem. Fraction *myFraction; myFraction is an object of type Fraction myFraction is used to store values from your new Fraction class • The allocation and initialization is often incorporated directly into the declaration line as follows: Fraction *myFraction = [[Fraction alloc] init];
Declaring and Setting values • Declaring Fraction *myFraction; • Relationship between myFraction and its data
Declaring and Setting values • Setting the fraction’s numerator and denominator
Unique Instance Variables • Unique instance variables Program 3.3
Choosing Names • Rules for forming names • must begin with a letter or underscore (_) • can be followed by any combination of letters (upper- or lowercase), underscores, or the digits 0–9. • Valid names sum, pieceFlag, I, myLocation, numberOfMoves, _sysFlag, ChessBoard • Invalid names sum$value-$ is not a valid character. piece flag-Embedded spaces are not permitted. 3Spencer -Names can’t start with a number. int-This is a reserved word. • Always remember that upper- and lowercase letters are distinct in Objective-C.
new method • new method • new method combines the actions of an alloc and init. • So the following line could be used to allocate and initialize a new Fraction Fraction *myFraction = [Fraction new]; • It’s generally better to use the two-step allocation and initialization approach. • You’re first creating a new object and then you’re initializing it.
Accessing Instance Variablesand Data Encapsulation • Create two new methods to access the corresponding instance variables of the Fraction (i.e. the receiver of the message) –(int) numerator; –(int) denominator; • Definitions for the methods –(int) numerator { return numerator; } –(int) denominator { return denominator; } Program 3.4
Summary • Now you know how to • define your own class, create objects or instances of that class. • send messages to those objects. • In later chapters, You’ll learn how to • pass multiple arguments to your methods. • divide your class definitions into separate files. • use key concepts such as inheritance and dynamic binding. • In the next chapter, you’ll learn more about data types and writing expressions in Objective-C.
Exercises • Define a class called XYPoint that will hold a Cartesian coordinate (x, y), where x and y are integers. Define methods to individually set the x and y coordinates of a point and retrieve their values. Write an Objective-C program to implement your new class and test it.
Data Types and Expressions • Basic Data Types • Arithmetic Expression • Assignment Operations • Defining a Calculator Class
Basic Data Types nil
Type id • Used to store an object of any type. (generic object) idgraphicObject; • Methods can be declared to return values of type id -(id) newObject: (int) type; • The id type is the basis for very important features in Objective-C know as polymorphism, dynamic binding and dynamic typing, which Chapter 9 discuss extensively.
Basic Data Types (cont’d) #import <Foundation/Foundation.h> int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int integerVar = 100; float floatingVar = 331.79; double doubleVar = 8.44e+11; char charVar = ‘W’; NSLog (@ ”integerVar = %i”, integerVar); NSLog (@”floatingVar = %f”, floatingVar); NSLog (@”doubleVar = %e”, doubleVar); NSLog (@”doubleVar = %g”, doubleVar); NSLog (@”charVar = %c”, charVar); [pool drain]; return0; } Program 4.1
Arithmetic Expressions • 『+』、『-』、『*』、『\』 • Operator Precedence • Integer Arithmetic and the Unary Minus Operator • The Modulus Operator Program 4.2 Program 4.3 Program 4.4
Basic Conversions • Floating to integer produces truncation int i1 = 123.75; //stores 123 • One floating term results in a floating result int i = 5; float f = i / 2.0; • Two integer terms results in an integer int i = 5; float f = i / 2; // store 2 into f Program 4.5
Basic Conversions (cont’d) • Typecast operator: (type) term • Typecast operator can be used to convert a term in an expression int i = 5, j = 2; float f = i / (float) j; //assigns 2.5 • Assignment Operators • General format: op = • e.g. count += 10; (is equivalent to count = count + 10) a /= b + c; • A Calculator Class Program 4.6
Exercises • Suppose you are developing a library of routines to manipulate graphical objects. Start by defining a new class called Rectangle. For now, just keep track of the rectangle’s width and height. Develop methods to set the rectangle’s width and height, retrieve these values, and calculate the rectangle’s area and perimeter. Assume that these rectangle objects describe rectangles on an integral grid, such as a computer screen. In that case, assume that the width and height of the rectangle are integer values. Here is the @interface section for the Rectangle class: