Скачать презентацию Introduction to Objective-C and i Phone Development 1 Скачать презентацию Introduction to Objective-C and i Phone Development 1

e6a9355e31315967f1c51f29876cd5fc.ppt

  • Количество слайдов: 57

Introduction to Objective-C and i. Phone Development 1 Introduction to Objective-C and i. Phone Development 1

Introduction • Objective-C is implemented as set of extensions to the C language. • Introduction • Objective-C is implemented as set of extensions to the C language. • It's designed to give C a full capability for objectoriented programming, and to do so in a simple and straightforward way. • Its additions to C are few and are mostly based on Smalltalk, one of the first object-oriented programming languages. 2

Why Objective C • Objective-C incorporates C, you get all the benefits of C Why Objective C • Objective-C incorporates C, you get all the benefits of C when working within Objective-C. • You can choose when to do something in an objectoriented way (define a new class, for example) and when to stick to procedural programming techniques (define a struct and some functions instead of a class). • Objective-C is a simple language. Its syntax is small, unambiguous, and easy to learn • Objective-C is the most dynamic of the object-oriented languages based on C. Most decisions are made at run time. 3

Object-Oriented Programming • The insight of object-oriented programming is to combine state and behavior, Object-Oriented Programming • The insight of object-oriented programming is to combine state and behavior, data and operations on data, in a high-level unit, an object, and to give it language support. • An object is a group of related functions and a data structure that serves those functions. The functions are known as the object's methods, and the fields of its data structure are its instance variables. 4

The Objective-C Language • The Objective-C language is fully compatible with ANSI standard C The Objective-C Language • The Objective-C language is fully compatible with ANSI standard C • Objective-C can also be used as an extension to C++. • Although C++ itself is a Object-Oriented Language, there are difference in the dynamic binding from Objective-C 5

Objective-C Language (cont. ) • Objective-C source files have a “. m” extension • Objective-C Language (cont. ) • Objective-C source files have a “. m” extension • “. h” file is the interface file • For example: – main. m – List. h (Interface of List class. ) – List. m (Implementation of List class. ) 6

ID • “id” is a data type used by Objective-C to define a pointer ID • “id” is a data type used by Objective-C to define a pointer of an object (a pointer to the object’s data) • Any type of object, as long as it is an object, we can use the id data type. • For example, we can define an object by: id an. Object; • nil is the reserved word for null object 7

Dynamic Typing • “id” data type has no information about the object • Every Dynamic Typing • “id” data type has no information about the object • Every object carries with it an isa instance variable that identifies the object's class, that is, what kind of object it is. • Objects are thus dynamically typed at run time. Whenever it needs to, the run-time system can find the exact class that an object belongs to, just by asking the object 8

Messages • To get an object to do something, you send it a message Messages • To get an object to do something, you send it a message telling it to apply a method. In Objective-C, message expressions are enclosed in square brackets [receiver message] • The receiver is an object. The message is simply the name of a method any arguments that are passed to it 9

Messages (cont. ) • For example, this message tells the my. Rect object to Messages (cont. ) • For example, this message tells the my. Rect object to perform its display method, which causes the rectangle to display itself [my. Rect display]; [my. Rect set. Origin: 30. 0 : 50. 0]; • The method set. Origin: : , has two colons, one for each of its arguments. The arguments are inserted after the colons, breaking the name apart 10

Polymorphism • Each object has define its own method but for different class, they Polymorphism • Each object has define its own method but for different class, they can have the same method name which has totally different meaning • The two different object can respond differently to the same message • Together with dynamic binding, it permits you to write code that might apply to any number of different kinds of objects, without having to choose at the time you write the code what kinds of objects they might be 11

Inheritance • Root class is NSObject • Inheritance is cumulative. A Square object has Inheritance • Root class is NSObject • Inheritance is cumulative. A Square object has the methods and instance variables defined for Rectangle, Shape, Graphic, and NSObject, as well as those defined specifically for Square 12

Inheritance (cont. ) • Instance Variables: The new object contains not only the instance Inheritance (cont. ) • Instance Variables: The new object contains not only the instance variables that were defined for its class, but also the instance variables defined for its super class, all the way back to the root class • Methods: An object has access not only to the methods that were defined for its class, but also to methods defined for its super class • Method Overriding: Implement a new method with the same name as one defined in a class farther up the hierarchy. The new method overrides the original; instances of the new class will perform it rather than the original 13

Class Objects • Compiler creates one class object to contain the information for the Class Objects • Compiler creates one class object to contain the information for the name of class and super class • To start an object in a class: id my. Rectx; my. Rect = [[Rectangle alloc] init]; • The alloc method returns a new instance and that instance performs an init method to set its initial state. 14

Defining a Class • In Objective-C, classes are defined in two parts: – An Defining a Class • In Objective-C, classes are defined in two parts: – An interface that declares the methods and instance variables of the class and names its super class – An implementation that actually defines the class (contains the code that implements its methods) 15

The Interface • The declaration of a class interface begins with the compiler directive The Interface • The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end @interface Class. Name : Its. Superclass { instance variable declarations } method declarations @end 16

Declaration • Instance Variables float width; float height; BOOL filled; NSColor *fill. Color; • Declaration • Instance Variables float width; float height; BOOL filled; NSColor *fill. Color; • Methods: • names of methods that can be used by class objects, class methods, are preceded by a plus sign + alloc • methods that instances of a class can use, instance methods, are marked with a minus sign: - (void) display; 17

Declaration (cont. ) • Importing the Interface: The interface is usually included with the Declaration (cont. ) • Importing the Interface: The interface is usually included with the #import directive #import "Rectangle. h" • To reflect the fact that a class definition builds on the definitions of inherited classes, an interface file begins by importing the interface for its super class • Referring to Other Classes: If the interface mentions classes not in this hierarchy, it must declare them with the @class directive: @class Rectangle, Circle; 18

The Implementation #import The Implementation #import "Class. Name. h" @implementation Class. Name method definitions @end - make. Identical. Twin { if ( !twin ) { twin = [[Sibling alloc] init]; twin->gender = gender; twin->appearance = appearance; } return twin; } 19

Implementation (cont. ) Example: @interface Worker : NSObject { char *name; @private int age; Implementation (cont. ) Example: @interface Worker : NSObject { char *name; @private int age; char *evaluation; @protected id job; float wage; @public id boss; } 20

Implementation (cont. ) - promote. To: new. Position { id old = job; job Implementation (cont. ) - promote. To: new. Position { id old = job; job = new. Position; return old; } 21

GCC and Objective-C • Objective-C is layered on top of the C language • GCC and Objective-C • Objective-C is layered on top of the C language • i. Phone & i. Pad “native” applications are written in Objective C • The Apple dev kit for Objective-C is called “Cocoa” • Can be written on any computer that has GCC plus “GNUstep” plug-in • Apple computers have all of this pre-installed, and also have an i. Phone simulator in the XCode IDE 22

Tools • Apple: pre-installed with the Cocoa frameworks – XCode or GCC in terminal Tools • Apple: pre-installed with the Cocoa frameworks – XCode or GCC in terminal window • Ubuntu: Gnu. Step is a free clone of Cocoa – – – sudo aptget install buildessentials gobjc gnustepmake gnustepcommon libgnustepbasedev • Windows: http: //www. gnustep. org/ 23

File Overview • Source code files have a. m extension • Header files have File Overview • Source code files have a. m extension • Header files have a. h extension • You can use gcc to compile in the same way as C code • But, you will need to add the Cacoa or GNUStep frameworks to the build. 24

Example: Hello World #import <Foundation/Foundation. h> int main (int argc, const char * argv[]) Example: Hello World #import int main (int argc, const char * argv[]) { NSAutorelease. Pool * pool = [[NSAutorelease. Pool alloc] init]; // insert code here. . . NSLog(@"Hello, World!"); [pool drain]; return 0; } NSLog() is equivalent to a C printf() Very similar to C C programs are valid in Objective-C 25

Compiling Hello World in Xcode (Mac) • File->New Project – Mac OS X category Compiling Hello World in Xcode (Mac) • File->New Project – Mac OS X category – Select Application – Command Line Tool – Type - “Foundation” • Name project helloworld and choose folder • Edit helloworld. m and paste in our example over the top of the default. The default code is this sample program. • Save. • Note that Foundation. framework has been included for us already • “Build and run”. • The debugger console should show “Hello World” 26

Compiling Hello World on Terminal (Mac) • Write hello. m using a plain text Compiling Hello World on Terminal (Mac) • Write hello. m using a plain text editor • To comple type: gcc – framework Foundation hello. m –o hello • Foundation brings in the Foundation framework (Cocoa) which • bundles together a set of dependencies (header files and libraries). You will need this every time we compile Objective C code. • Type: . /hello will run the program in the terminal • Note: this approach is fine for early examples but the i. Phone applications will be much easier to build in XCode. 27

Intro to Hello. World • Objective-C uses a string class similar to the std: Intro to Hello. World • Objective-C uses a string class similar to the std: : string or Java string. It is called NSString. • Constant NSStrings are preceded by @ for example: @”Hello World” • You will notice that NSLog() also outputs time and date and various extra information. • NSAutorelease. Pool* pool =[[NSAutorelease. Pool • alloc] init]; allocates a lump of memory • Memory must be freed with [pool drain]; 28

Example 2 #import <Foundation/Foundation. h> int main(int argc, const char* argv[]) { NSAutorelease. Pool* Example 2 #import int main(int argc, const char* argv[]) { NSAutorelease. Pool* pool = [[NSAutorelease. Pool alloc] init]; NSLog (@”Hello World”); int undergrads = 120; int postgrads = 50; int students = undergrads + postgrads; NSLog (@”Now featuring. . . n %i Computer Science students”, students); [pool drain]; return 0; } 29

Some things to note • No line break needed at end of NSLog statements. Some things to note • No line break needed at end of NSLog statements. • NSString constants use C-style variables. • Test this program to see results. 30

@interface Class. Name : Parent. Class. Name { declare member variable here; declare another @interface Class. Name : Parent. Class. Name { declare member variable here; declare another member variable here; } declare method functions here; @end • • Equivalent to C class declaration Goes in header (. h) file Functions outside curly braces Don’t forget the @end tag 31

@implementation #import <Foundation/Foundation. h> #include @implementation #import #include "Computer. Science. h“ @implementation Class. Name define method function here; define another method function here; define yet another method function here; @end ● Equivalent to C class function definitions ● Goes in source (. m) file ● Don't forget the @end tag 32

Example 3: Computer. Science. h @interface Computer. Science : NSObject { int m. Undergrads; Example 3: Computer. Science. h @interface Computer. Science : NSObject { int m. Undergrads; int m. Postgrads; } -(void) print; -(void) set. Undergrads: (int) undergrads; -(void) set. Postgrads: (int) postgrads; @end 33

Some things to note • NSObject is the “root” object in Objective-C • No Some things to note • NSObject is the “root” object in Objective-C • No direct access to instance variables so we write some get/set “instance methods” • Instance methods (affect internal state of class) are preceded with a minus sign • “Class methods” (higher level functions) are preceded with a plus sign e. g. create new class • Method return type in parentheses • Semicolon before list of parameters • Parameter type in parenthesis, followed by name 34

Example 3: Computer. Science. m #include “Computer. Science. h” @implementation Computer. Science -(void) print Example 3: Computer. Science. m #include “Computer. Science. h” @implementation Computer. Science -(void) print { int total. Students = m. Undergrads + m. Postgrads; NSLog (@”Total students in Comp. Sci = %i”, total. Students); } -(void) set. Undergrads: (int) undergrads { m. Undergrads = undergrads; } -(void) set. Postgrads: (int) postgrads { m. Postgrads = postgrads; } @end 35

Some things to note • Note prefix minus sign • Very similar to C Some things to note • Note prefix minus sign • Very similar to C • Same format as with the interface 36

Example 2: main. m #import <Foundation/Foundation. h> #include “Computer. Science. h” int main(int argc, Example 2: main. m #import #include “Computer. Science. h” int main(int argc, char* argv[]) { NSAutorelease. Pool* pool = [[NSAutorelease. Pool alloc] init]; Computer. Science* itu. Comp. Sci; // pointer itu. Comp. Sci = [Computer. Science alloc]; // allocate memory itu. Comp. Sci = [itu. Comp. Sci init]; // initialize [itu. Comp. Sci set. Undergrads: 120]; // apply method to instance [itu. Comp. Sci set. Postgrads: 2000]; [itu. Comp. Sci print]; [itu. Comp. Sci release]; [pool drain]; return 0; } 37

Some things to note • Applying methods to instance format: [receiver message]; • Semi-colon Some things to note • Applying methods to instance format: [receiver message]; • Semi-colon for variables or values passed to methods • [pool drain] etc. are also applying methods. • Built-in messages; alloc, init, release. 38

Some other things to note • alloc is equivalent to C++ new but it Some other things to note • alloc is equivalent to C++ new but it also zeros all variables • init should be applied to an instance before use • These are often combined in shorthand: Computer. Science* itu. Comp. Sci = [[Computer. Science alloc] init]; • There is no garbage collection on the i. Phone, so we should release all of our instance memory. 39

To compile example 3 • • Create a project in Xcode Delete the original To compile example 3 • • Create a project in Xcode Delete the original main. m Add existing files to the project Compile and run! 40

Data Structures • Objective-C arrays are similar to C arrays, but you can initialize Data Structures • Objective-C arrays are similar to C arrays, but you can initialize whole array in a list. • Or just a few indices of the array. The rest are set to 0. • Or mix and match; the example will create an array of size [8]. int values[3] = { 3, 4, 2 }; char letters[3] = { 'a', 'c', 'x' }; float grades[100] = {10. 0, 11. 2, 1. 1}; int array[] = {[3]=11, [2]=1, [7]=0}; 41

Multi-dimensional Arrays • Can be initialized by using subset notation with braces. Note no Multi-dimensional Arrays • Can be initialized by using subset notation with braces. Note no comma after second subset. • Subset braces are optional, the compiler will fill in blanks where it can as with 1 D arrays. int array[2][3] = { { 0, 3, 4}, { 1, 1, 1} }; int array[2][3] = {0, 3, 4, 1, 1, 1}; 42

Arrays and Functions • Arrays can be passed as arguments to functions. • This Arrays and Functions • Arrays can be passed as arguments to functions. • This function will print every integer in an array but it needs to also be told how long the array is (array. Length). • Statements with hard-coded indices such as array[4] are potentially dangerous. void function(int array[], int array. Length) { int fourth. Value = array[4]; for (int i = 0; i < array. Length; i++) { NSLog(@”%i”, array[i]; } } 43

Structs • Similarly the Objective C “struct” can be • initialized in one go. Structs • Similarly the Objective C “struct” can be • initialized in one go. • Use the '. ' member notation or just use values in the correct order or use some values. 'unknown. ' • In the following example we explicitly define the last member, but the others are undefined. 44

Structs struct Computer. Science { int BSYears; int Ph. DYears; int Well. Spent. Years; Structs struct Computer. Science { int BSYears; int Ph. DYears; int Well. Spent. Years; }; struct Computer. Science my. Career = { . BSYears = 3, . Ph. DYears = 3, . Well. Spent. Years = 6 }; struct Computer. Science poor. Life. Decisions = { 3, 8, 3 }; struct Computer. Science unknown = { 3 }; struct Computer. Science and. Further. More = {. Well. Spent. Years = 0 }; 45

Declare+Define a Struct in One • Similar to the older C-style notation. • The Declare+Define a Struct in One • Similar to the older C-style notation. • The example will declare a coffee order struct and immediately define an instance called “complexity. Group”. struct coffee. Order { int Plain; int Double. Espresso; } complexity. Group = { 7, 4 }; 46

Fitting into limited memory: Bit fields • To work on devices with memory limitations Fitting into limited memory: Bit fields • To work on devices with memory limitations we can manually define the bit size of variables. • Using a struct, all of the members are packed together efficiently. • The next example divides a 16 -bit unsigned integer into 3 on/off bit flags, a 10 -bit number and a 3 -bit number. • Note that it is valid to use Boolean operations on single bit variables. 47

Fitting into limited memory: Bit fields struct Alarm. Panel. Struct { unsigned int Door. Fitting into limited memory: Bit fields struct Alarm. Panel. Struct { unsigned int Door. Alarm. Triggered: 1; unsigned int Window. Alarm. Triggered: 1; unsigned int Trapdoor. Alarm. Triggered: 1; unsigned int Administrators. ID: 10; unsigned int Alarm. Key. Code: 3; }; struct Alarm. Panel. Struct lab; lab. Alarm. Code = 1; lab. Door. Alarm. Triggered = 0; if (Door. Alarm. Triggered). . . 48

Fitting into limited memory: Unions • Union data structures allow ambiguity. • Useful for Fitting into limited memory: Unions • Union data structures allow ambiguity. • Useful for allowing one storage area to hold different variable types. • Can only hold one of the variables at a time. • Must be careful to ensure retrieval type matches last type stored. • Might come in handy for storing lists of “data” that might be of different types. • The next example gives ones potentially practical use; • A series of recordings store ‘Data. ’ • The struct has a char to indicate the type of data recorded in Data. 49

Fitting into limited memory: Unions union One. Of. The. Following { char Letter; int Fitting into limited memory: Unions union One. Of. The. Following { char Letter; int Count. Of; float Average; }; One. Of. The. Following last. Space. On. The. Phone; last. Space. On. The. Phone. Letter = 'a'; last. Space. On. The. Phone. Count. Of = 1; struct Recorded. Data { char* Name; union { float Real. Number; int Integer; char Letter; } Data; // immediately defines an instance char Type. Of. Data; } array. Of. Recorded. Data[100]; 50

Simulated i. OS Apps • • Relies heavily on the XCode IDE. i. Phone Simulated i. OS Apps • • Relies heavily on the XCode IDE. i. Phone and i. Pad Simulator program is a free add-on for Xcode. You just need a Mac computer to develop an i. OS app. Running or testing apps on an actual device is not free (~100 USD/year). The process of deploying an app to a device is quite involved. 1. Software set-up 2. Developer sign-up 3. Member sign-up 4. Certificate request Software comes as one bundle Latest Xcode plus Simulators Apple Organizer GUI designer 51

Something to note! • You can program for either the i. Phone or the Something to note! • You can program for either the i. Phone or the i. Pad or both in the latest XCode. • If you are going to do the examples for both simultaneously be aware that there are two sets of. h and. m files (one for each). 52

Frameworks • UIKit. framework for developing standard i. OS GUIs (buttons etc. ) • Frameworks • UIKit. framework for developing standard i. OS GUIs (buttons etc. ) • UIText. Field (user-entered text that brings up the keyboard) • UIFont • UIView • UITable. View • UIImage • UIButton (a click-able button) • UILabel (a string of text on-screen) • UIWindow (main Window on i. Phone) 53

i. OS programming • Event driven framework • Interface Designer has some extra macros i. OS programming • Event driven framework • Interface Designer has some extra macros for the code that act like hooks to variables; – IBAction - trigger events like mouse clicks – IBOutlet - captures outputs from events • These tags are not compiled (don't affect the code) but sit as an extra before variables that the Interface Designer can see. 54

Start a New XCode i. OS Project • New Project → i. Phone/i. Pad Start a New XCode i. OS Project • New Project → i. Phone/i. Pad OS • Navigation-Based - “navigation controller” as used in Contacts app. • Open. GL ES - cut-down Open. GL • Tab Bar – app in style of i. Pod app. • Utility – Flipside app in style of stock quote app. • View-Based – single view that you draw into and display to screen. • Window-Based – basic app with a main window. (we will use this one for examples. ) 55

Try Out - Hello World • Watch the Hello World tutorial and build your Try Out - Hello World • Watch the Hello World tutorial and build your first i. Phone application. • The tutorial can be found at: http: //www. youtube. com/watch? v=l. Rt 5 v. Epue. Q 56

End of Lecture 1 • Next time, we will be doing more Object-C programming End of Lecture 1 • Next time, we will be doing more Object-C programming and building more i. Phone applications. • Make sure to practice with the “Hello World” application before next week so you can move forward with more complex concepts and programming methods. 57