1 / 66

Overview of Objective-C

Overview of Objective-C. Objective-C is an object oriented language. follows ANSI C style coding with methods from Smalltalk There is no formal written standard Relies mostly on libraries written by others Flexible almost everything is done at runtime. Dynamic Binding Dynamic Typing

torn
Download Presentation

Overview of Objective-C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Overview of Objective-C • Objective-C is an object oriented language. • follows ANSI C style coding with methods from Smalltalk • There is no formal written standard • Relies mostly on libraries written by others • Flexible almost everything is done at runtime. • Dynamic Binding • Dynamic Typing • Dynamic Linking

  2. Inventors • Objective-C was invented by two men, Brad Cox and Tom Love. • Both were introduced to Smalltalk at ITT in 1981 • Cox thought something like Smalltalk would be very useful to application developers • Cox modified a C compiler and by 1983 he had a working Object-oriented extension to C called OOPC.

  3. Development • Tom Love acquired a commercial copy of Smalltalk-80 while working for Schlumberger Research • With direct access Smalltalk, Love added more to OOPC making the final product, Objective-C. • In 1986 they release Objective-C through their company “Stepstone”

  4. NeXT and NeXTSTEP • In 1988 Steve Jobs acquires Objective-C license for NeXT • Used Objective-C to build the NeXTSTEP Operating System • Objective-C made interface design for NeXTSTEP much easier • NeXTSTEP was derived from BSD Unix • In 1995 NeXT gets full rights to Objective-C from Stepstone

  5. OPENSTEP API • Developed in 1993 by NeXT and Sun • An effort to make NeXTSTEP-like Objective-C implementation available to other platforms. • In order to be OS independent • Removed dependency on Mach Kernel • Made low-level data into classes • Paved the way for Mac OS X, GNUstep

  6. Apple and Mac OS X • NeXT is taken over by Apple in 1996 and put Steve Jobs and his Objective-C libraries to work • Redesigned Mac OS to use objective-C similar to that of NeXTSTEP • Developed a collection of libraries named “Cocoa” to aid GUI development • Release Mac OS X (ten), which was radically different than OS 9, in March 2001

  7. The Cocoa API • Primarily the most frequently used frameworks nowadays. • Developed by Apple from NeXTSTEP and OPENSTEP • Has a set of predefined classes and types such as NSnumber, NSstring, Nsdate, etc. • NS stands for NeXT-sun • Includes a root class NSObject where words like alloc, retain, and release come from

  8. Dynamic Language • Almost everything is done at runtime • Uses dynamic typing, linking, and binding • This allows for greater flexibility • Minimizes RAM and CPU usage

  9. To Import or Include? • C/C++’s #include will insert head.h into the code even if its been added before. • Obj-C’s #import checks if head.h has been imported beforehand. #import head.h

  10. Messages • Almost every object manipulation is done by sending objects a message • Two words within a set of brackets, the object identifier and the message to send. • Because of dynamic binding, the message and receiver are joined at runtime [Identifier message ]

  11. Basic syntax structure C++ syntax void function(int x, int y, char z); Object.function(x, y, z); Objective-C syntax -(void) function:(int)x, (int)y, (char)z; [Object function:x, y, z];

  12. The word ‘id’ indicates an identifier for an object much like a pointer in c++ This uses dynamic typing For example, if Pen is a class… Keyword: id extern id Pen; id myPen; myPen = [Pen new ];

  13. Memory Allocation • Objects are created dynamically through the keyword, “alloc” • Objects are dynamically deallocated using the words “release” and “autorelease” • autorelease dealocates the object once it goes out of scope. • NOTE: None of these words are built-in

  14. Ownership • Objects are initially owned by the id that created them. • Like C pointers, multiple IDs can use the same object. • However, like in C if one ID releases the object, then any remaining pointers will be referencing invalid memory. • A method like “retain” can allow the object to stay if one ID releases it.

  15. Prototyping functions • When declaring or implementing functions for a class, they must begin with a + or - • + indicates a “class method” that can only be used by the class itself. In other words, they’re for private functions. • - indicates “instance methods” to be used by the client program (public functions).

  16. Class Declaration (Interface) node.h @interface Node : NSObject { Node *link; int contents; } +(id)new; -(void)setContent:(int)number; -(void)setLink:(Node*)next; -(int)getContent; -(Node*)getLink; @end

  17. Class Definition (Implementation) node.m #import "node.h” @implementation Node +(id)new { return [Node alloc];} -(void)setContent:(int)number {contents = number;} -(void)setLink:(Node*)next { [link autorelease]; link = [next retain]; } -(int)getContent {return contents;} -(Node*)getLink {return link;} @end

  18. Adds OOP, meta programming and generic programming to C Comes with a std library Has numerous uses Large and complex code for OOP Only adds OOP to C Has no standard library; is dependant on other libraries Mostly used for application building Simpler way of handling classes and objects C++ VS. Objective-C

  19. Objective-C 2.0 • In October 2007, Apple Inc. releases Objective-C 2.0 for Mac OS 10.5 (Leopard) • Adds automatic garbage collection • Instance Methods (public functions) are defined differently using @property

  20. #import "linkList.h" @implementation linkList +(id)new {return [linkList alloc];} -(void)insert:(int)value { id temp = [Node new]; [temp setContent:value]; [temp setLink:head]; head = [temp retain]; [temp release]; } -(void)append:(int)value { id last = [head getLink]; while ([last getLink] != nil) {last = [last getLink];} id temp = [Node new]; [temp setContent:value]; [last setLink:temp]; [temp release]; } -(void)remove { id temp = head; head = [head getLink]; [temp release]; } -(int)getValue { return [head getContent];} @end linkList class linkList.m

  21. #import "linkList.h” @interface Stack : linkList {} +(id)new; -(void)push:(int)value; -(int)pop; @end #import "stack.h” @implementation Stack +(id)new {return [Stack alloc];} -(void)push:(int)value {[self insert:value];} -(int)pop { int ret = [self getValue]; [self remove]; return ret; } @end Stack class stack.h stack.m

  22. #import "stack.h” int main(){ Stack *s = [Stack new]; [s push:1]; [s push:2]; printf("%d\t", [s pop]); [s push:3]; printf("%d\t", [s pop]); printf("%d\t", [s pop]); [s release]; return 0; } Example: main.c main.c $ gcc -x objective-c node.m linkList.m stack.m main.c -framework Cocoa -o stackTest $./stackTest 2 3 1

  23. C and Objective-C Programming

  24. Why learn C? • Objective-C is based on C • Better control of low-level mechanisms • Performance better than Java • Java hides many details needed for writing OS code But,…. • Memory management responsibility • Explicit initialization and error detection • More room for mistakes

  25. Goals of this tutorial • To introduce some basic C concepts to you • so that you can read further details on your own • To warn you about common mistakes made by beginners • so that you get your homework done quickly • You can write more complicated code

  26. Simple Example #include <stdio.h> void main(void) { printf(“Hello World. \n \t and you ! \n ”); /* print out a message */ return; } $Hello World. and you ! $

  27. Summarizing the Example • #include <stdio.h> = include header file stdio.h • No semicolon at end • Small letters only – C is case-sensitive • void main(void){ … } is the only code executed • printf(“ /* message you want printed */ ”); • \n = newline \t = tab • Dessert: \ in front of other special characters within printf. • printf(“Have you heard of \”The Rock\” ? \n”);

  28. Simple Data Types • data-type # bytes(typical) values short-hand • int               4       -2,147,483,648 to 2,147,483,647 %d • char              1       -128 to 127 %c • float             4       3.4E+/-38 (7 digits) %f • double            8       1.7E+/-308 (15 digits long) %lf • long              4       -2,147,483,648 to 2,147,483,647 %l • short             2       -32,768 to 32,767 • Lookup: • signed / unsigned - int, char, long, short • long double • ex: • int num=20000; • printf(“Cornell has about %d students.\n”, num);

  29. Example ! #include <stdio.h> void main(void) { int nstudents = 0; /* Initialization, required */ printf(“How many students does ITU have ?:”); scanf (“%d”, &nstudents); /* Read input */ printf(“ITU has %d students.\n”, nstudents); return ; } $How many students does ITU have ?: 20000 (enter) ITU has 20000 students. $

  30. Type conversion #include <stdio.h> void main(void) { int i,j = 12; /* i not initialized, only j */ float f1,f2 = 1.2; i = (int) f2; /* explicit: i <- 1, 0.2 lost */ f1 = i; /* implicit: f1 <- 1.0 */ f1 = f2 + (int) j; /* explicit: f1 <- 1.2 + 12.0 */ f1 = f2 + j; /* implicit: f1 <- 1.2 + 12.0 */ } • Explicit conversion rules for arithmetic operation x=y+z; • convert y or z as • double <- float <- int <- char, short • then type cast it to x ’s type • Moral: stick with explicit conversions - no confusion !

  31. Like Java, like C • Operators same as Java: • Arithmetic • int i = i+1; i++; i--; i *= 2; • +, -, *, /, %, • Relational and Logical • <, >, <=, >=, ==, != • &&, ||, &, |, ! • Syntax same as in Java: • if ( ) { } else { } • while ( ) { } • do { } while ( ); • for(i=1; i <= 100; i++) { } • switch ( ) {case 1: … } • continue; break;

  32. Example • #include <stdio.h> • #define DANGERLEVEL 5 /* C Preprocessor - • - substitution on appearance */ • /* like Java ‘final’ */ • void main(void) • { • float level=1; • /* if-then-else as in Java */ • if (level <= DANGERLEVEL){ /*replaced by 5*/ • printf(“Low on gas!\n”); • } • else printf(“Good driver !\n”); • return; • }

  33. One-Dimensional Arrays #include <stdio.h> void main(void) { int number[12]; /* 12 cells, one cell per student */ int index, sum = 0; /* Always initialize array before use */ for (index = 0; index < 12; index++) { number[index] = index; } /* now, number[index]=index; will cause error:why ?*/ for (index = 0; index < 12; index = index + 1) { sum += number[index]; /* sum array elements */ } return; }

  34. More arrays • Strings char name[6]; name = {‘C’,’S’,’4’,’1’,’4’,’\0’}; /* ’\0’= end of string */ printf(“%s”, name); /* print until ‘\0’ */ • Functions to operate on strings • strcpy, strncpy, strcmp, strncmp, strcat, strncat, strstr,strchr • #include <strings.h> at program start • Multi-dimensional arrays int points[3][4]; points [1][3] = 12; /* NOT points[3,4] */ printf(“%d”, points[1][3]);

  35. Like Java, somewhat like C • Type conversions • but you can typecast from any type to any type • c = (char) some_int; • So be careful ! • Arrays • Always initialize before use • int number[12]; printf(“%d”, number[20]); • produces undefined output, may terminate, may not even be detected. • Strings are terminated by ’\0’ character char name[6] = {‘C’,’S’,’4’,’1’,’4’,’\0’}; /* ’\0’= end of string */ printf(“%s”, name); /* print until ‘\0’ */

  36. Memory layout and addresses int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘c’, d = ‘d’; 5 10 12.5 9. 8 c d 4300 4304 4308 4312 4316 4317

  37. Pointers made easy - 1 any float f f_addr ? ? ? any address 4300 4304 f f_addr ? 4300 4300 4304 • Pointer = variable containing address of another variable • float f; /* data variable */ • float *f_addr; /* pointer variable */ • f_addr = &f; /* & = address operator */

  38. Pointers made easy - 2 f f_addr 3.2 1.3 4300 4300 4300 4304 f f_addr 4300 4304 *f_addr = 3.2; /* indirection operator */ float g=*f_addr; /* indirection:g is now 3.2 */ f = 1.3;

  39. Pointer Example #include <stdio.h> void main(void) { int j; int *ptr; ptr=&j; /* initialize ptr before using it */ /* *ptr=4 does NOT initialize ptr */ *ptr=4; /* j <- 4 */ j=*ptr; /* j <- ??? */ }

  40. Dynamic Memory allocation #include <stdio.h> void main(void) { int *ptr; /* allocate space to hold an int */ ptr = malloc(sizeof(int)); /* do stuff with the space */ *ptr=4; free(ptr); /* free up the allocated space */ } • Explicit allocation and de-allocation

  41. Elementary file handling • #include <stdio.h> • void main(void) { • /* file handles */ • FILE *input_file=NULL; • /* open files for writing*/ • input_file = fopen(“cwork.dat”, “w”); • if(input_file == NULL) • exit(1); /* need to do explicit ERROR CHECKING */ • /* write some data into the file */ • fprintf(input_file, “Hello there”); • /* don’t forget to close file handles */ • fclose(input_file); • return; • }

  42. Error Handling • Moral from example: • unlike Java, no explicit exceptions • need to manually check for errors • Whenever using a function you’ve not written • Anywhere else errors might occur

  43. If a program is too long Modularization – easier to code debug Code reuse Passing arguments to functions By value By reference Returning values from functions By value By reference Functions - why and how ?

  44. Functions – basic example • #include <stdio.h> • int sum(int a, int b); • /* function prototype at start of file */ • void main(void){ • int total = sum(4,5); /* call to the function */ • printf(“The sum of 4 and 5 is %d”, total); • } • int sum(int a, int b){ /* the function itself • - arguments passed by value*/ • return (a+b); /* return by value */ • }

  45. Arguments by reference • #include <stdio.h> • int sum(int *pa, int *pb); • /* function prototype at start of file */ • void main(void){ • int a=4, b=5; • int *ptr = &b; • int total = sum(&a,ptr); /* call to the function */ • printf(“The sum of 4 and 5 is %d”, total); • } • int sum(int *pa, int *pb){ /* the function itself • - arguments passed by reference */ • return (*pa+*pb); /* return by value */ • }

  46. Why pointer arguments?! #include <stdio.h> void swap(int, int); main() { int num1 = 5, num2 = 10; swap(num1, num2); printf(“num1 = %d and num2 = %d\n”, num1, num2); } void swap(int n1, int n2) { /* passed by value */ int temp; temp = n1; n1 = n2; n2 = temp; }

  47. Why pointer arguments? This is why #include <stdio.h> void swap(int *, int *); main() { int num1 = 5, num2 = 10; swap(&num1, &num2); printf(“num1 = %d and num2 = %d\n”, num1, num2); } void swap(int *n1, int *n2) { /* passed and returned by reference */ int temp; temp = *n1; *n1 = *n2; *n2 = temp; }

  48. What’s wrong with this ? #include <stdio.h> void dosomething(int *ptr); main() { int *p; dosomething(p) printf(“%d”, *p); /* will this work ? */ } void dosomething(int *ptr){ /* passed and returned by reference */ int temp=32+12; ptr = &(temp); } /* compiles correctly, but gives run-time error */

  49. Passing and returning arrays #include <stdio.h> void init_array(int array[], int size) ; void main(void) { int list[5]; init_array(list, 5); for (i = 0; i < 5; i++) printf(“next:%d”, array[i]); } void init_array(int array[], int size) { /* why size ? */ /* arrays ALWAYS passed by reference */ int i; for (i = 0; i < size; i++) array[i] = 0; }

  50. Data - stack Memory layout of programs 0 100 400 560 1010 1200 Header info Code all malloc()s Data - Heap Dynamic memory Local memory + function call stack all normal vars

More Related