Académique Documents
Professionnel Documents
Culture Documents
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
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.
2
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
3
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
Dynamic Language
Almost everything is done at runtime Uses dynamic typing, linking, and binding This allows for greater flexibility Minimizes RAM and CPU usage
To Import or Include?
#import head.h
C/C++s #include will insert head.h into the code even if its been added before. Obj-Cs #import checks if head.h has been imported beforehand.
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.
[Identifier message ]
Because of dynamic binding, the message and receiver are joined at runtime
10
Objective-C syntax
-(void) function:(int)x, (int)y, (char)z;
[Object function:x, y, z];
11
Keyword: id
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 extern id Pen; id myPen; myPen = [Pen new ];
12
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
13
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.
14
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, theyre for private functions. - indicates instance methods to be used by the client program (public functions).
15
@interface Node : NSObject { Node *link; int contents; } +(id)new; -(void)setContent:(int)number; -(void)setLink:(Node*)next; -(int)getContent; -(Node*)getLink; @end
16
17
C++
VS.
Objective-C
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
18
Adds OOP, meta programming and generic programming to C Comes with a std library Has numerous uses Large and complex code for OOP
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
19
linkList class
#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]; }
linkList.m
-(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
20
Stack class
#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.h
stack.m
21
Example: main.c
#import "stack.h int main(){ Stack *s = [Stack [s push:1]; [s push:2]; printf("%d\t", [s [s push:3]; printf("%d\t", [s printf("%d\t", [s [s release]; return 0; }
main.c
new];
$ gcc -x objective-c node.m linkList.m stack.m main.c -framework Cocoa -o stackTest $./stackTest 2 3 1
22
23
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
24
25
Simple Example
#include <stdio.h> void main(void) { printf(Hello World. \n \t and you ! \n ); /* print out a message */ return; }
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.
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. $
29
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; f1 = i; /* explicit: i <- 1, 0.2 lost */ /* implicit: f1 <- 1.0 */
30
31
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; }
32
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;
33
More arrays
Strings
char name[6]; name = {C,S,4,1,4,\0}; /* \0= end of string */ printf(%s, name); /* print until \0 */
Multi-dimensional arrays
So be careful !
Arrays
Always initialize before use
int number[12]; printf(%d, number[20]);
10
12.5
9. 8
4300
4304
4308
4312
4316 4317
36
f_addr
? 4300
? 4304
? 4300
4300 4304
37
3.2 4300
4300 4304
1.3 4300
4300 4304
38
Pointer Example
#include <stdio.h>
*ptr=4; j=*ptr; }
39
40
Error Handling
Moral from example:
unlike Java, no explicit exceptions need to manually check for errors
Whenever using a function youve not written Anywhere else errors might occur
42
43
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 */ } 45
void dosomething(int *ptr){ /* passed and returned by reference */ int temp=32+12; ptr = &(temp); } /* compiles correctly, but gives run-time error */
48
Header info
100 Code 400
all malloc()s
560
Data - Heap
Dynamic memory
Data - stack
hw.c
mypgm.c
void myproc(void); int mydata;
Library headers
Standard User-defined
mypgm.h
51
Externs
#include <stdio.h> extern char user2line [20]; char user1line[30]; void dummy(void); void main(void) { char user1line[20]; . . . } /* global variable defined in another file */ /* global for this file */
52
Structures
Equivalent of Javas classes with only data (no methods)
#include <stdio.h> struct birthday{ int month; int day; int year; }; main() { struct birthday mybday; /* - no new needed ! */ /* then, its just like Java ! */ mybday.day=1; mybday.month=1; mybday.year=1977; printf(I was born on %d/%d/%d, birth.day, birth.month, birth.year); } 53
More on Structures
struct person{ char name[41]; int age; float height; struct { int month; int day; int year; } birth; }; struct person me; me.birth.year=1977; struct person class[60]; /* array of info about everyone in class */ class[0].name=Gun; class[0].birth.year=1971;
54
/* embedded structure */
Passing/Returning a structure
/* pass struct by value */ void display_year_1(struct birthday mybday) { printf(I was born in %d\n, mybday.year); } /* - inefficient: why ? */ . . . . /* pass struct by reference */ void display_year_2(struct birthday *pmybday) { printf(I was born in %d\n, pmybday->year); /* warning ! ->, not ., after a struct pointer*/ } . . . . /* return struct by value */ struct birthday get_bday(void){ struct birthday newbday; newbday.year=1971; /* . after a struct */ return newbday; } /* - also inefficient: why ? */
55
/* JANUARY is the same as month.JANUARY */ /* alternatively, . */ enum month{ JANUARY=1, FEBRUARY, MARCH };
56
typedef struct person Person; Person me; /* same as struct person me; */
typedef struct person *Personptr; Personptr ptrtome; /* same as struct person *ptrtome;*/
57
More pointers
int month[12]; /* month is a pointer to base address 430*/ month[3] = 7; /* month address + 3 * int elements => int at address (430+3*4) is now 7 */
ptr = month + 2; /* ptr points to month[2], => ptr is now (430+2 * int elements)= 438 */ ptr[5] = 12; /* ptr address + 5 int elements => int at address (434+5*4) is now 12. Thus, month[7] is now 12 */ ptr++; /* ptr <- 438 + 1 * size of int = 442 */ (ptr + 4)[2] = 12; /* accessing ptr[6] i.e., array[9] */
Now , month[6], *(month+6), (month+4)[2], ptr[3], *(ptr+3) are all the same integer variable.
58
2-D arrays
2-dimensional array
int weekends[52][2];
[0][0]
[0][1]
[1][0]
[1][1]
[2][0]
[2][1]
[3][0]
. . .
weekends
59
60
Strings
#include <stdio.h> main() char char char { msg[10]; /* array of 10 chars */ *p; /* pointer to a char */ msg2[]=Hello; /* msg2 = Hello\0 */
msg = Bonjour; /* ERROR. msg has a const address.*/ p = Bonjour; /* address of Bonjour goes into p */ msg = p; /* ERROR. Message has a constant address. */ /* cannot change it. */ p = msg; /* OK */ p[0] = H, p[1] = i,p[2]=\0; /* *p and msg are now Hi */
61
Pointer to function
func(); /*function returning integer*/ *func(); /*function returning pointer to integer*/ (*func)(); /*pointer to function returning integer*/ *(*func)(); /*pointer to func returning ptr to int*/
/* do something with d */
63
64
65
References
Cox, Brad. Object Oriented Programming: an Evolutioary Approach Sebesta, Robert. Concepts of Programming Languages Apple Inc. Apple Developer Connection
http://developer.apple.com
66