Oc Overview
-
Upload
hassan-khwileh -
Category
Documents
-
view
213 -
download
0
Transcript of Oc Overview
-
7/28/2019 Oc Overview
1/66
1
Overview of Objective-C
Objective-C is an object oriented language.
follows ANSI C style coding with methods fromSmalltalk
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
-
7/28/2019 Oc Overview
2/66
2
Inventors
Objective-C was invented by two men, BradCox and Tom Love.
Both were introduced to Smalltalk at ITT in
1981 Cox thought something like Smalltalk
would be very useful to applicationdevelopers
Cox modified a C compiler and by 1983 hehad a working Object-oriented extension toC called OOPC.
-
7/28/2019 Oc Overview
3/66
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
-
7/28/2019 Oc Overview
4/66
4
NeXT and NeXTSTEP
In 1988 Steve Jobs acquires Objective-Clicense 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
-
7/28/2019 Oc Overview
5/66
5
OPENSTEP API
Developed in 1993 by NeXT and Sun
An effort to make NeXTSTEP-likeObjective-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
-
7/28/2019 Oc Overview
6/66
6
Apple and Mac OS X
NeXT is taken over by Apple in 1996 andput Steve Jobs and his Objective-C librariesto work
Redesigned Mac OS to use objective-Csimilar to that of NeXTSTEP
Developed a collection of libraries namedCocoa to aid GUI development
Release Mac OS X (ten), which wasradically different than OS 9, in March2001
-
7/28/2019 Oc Overview
7/66
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 forNeXT-sun Includes a root class NSObject where words like
alloc, retain, and release come from
-
7/28/2019 Oc Overview
8/66
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
-
7/28/2019 Oc Overview
9/66
9
To Import or Include?
C/C++s #include will insert head.h into
the code even if its been added before.
Obj-Cs #import checks ifhead.h has
been imported beforehand.
#import head.h
-
7/28/2019 Oc Overview
10/66
10
Messages
Almost every object manipulation is done
by sending objects a message
Two words within a set of brackets, theobject identifier and the message to send.
Because of dynamic binding, the message
and receiver are joined at runtime
[Identifier message ]
-
7/28/2019 Oc Overview
11/66
11
Basic syntax structure
C++ syntax
Objective-C syntax
void function(int x, int y, char z);
Object.function(x, y, z);
-(void) function:(int)x, (int)y, (char)z;
[Object function:x, y, z];
-
7/28/2019 Oc Overview
12/66
12
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 ];
-
7/28/2019 Oc Overview
13/66
13
Memory Allocation
Objects are created dynamically through the
keyword, alloc
Objects are dynamically deallocated usingthe words release and autorelease
autorelease dealocates the object once it
goes out of scope.
NOTE: None of these words are built-in
-
7/28/2019 Oc Overview
14/66
14
Ownership
Objects are initially owned by the id thatcreated 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.
-
7/28/2019 Oc Overview
15/66
15
Prototyping functions
When declaring or implementing functions
for a class, they must begin with a + or -
+ indicates a class method that can onlybe used by the class itself. In other words,
theyre for private functions.
- indicates instance methods to be used by
the client program (public functions).
-
7/28/2019 Oc Overview
16/66
16
Class Declaration (Interface)
@interface Node : NSObject {
Node *link;
int contents;
}+(id)new;
-(void)setContent:(int)number;
-(void)setLink:(Node*)next;
-(int)getContent;-(Node*)getLink;
@end
node.h
-
7/28/2019 Oc Overview
17/66
17
Class Definition (Implementation)#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
node.m
-
7/28/2019 Oc Overview
18/66
18
C++ VS. Objective-C
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 ofhandling classes and
objects
-
7/28/2019 Oc Overview
19/66
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
-
7/28/2019 Oc Overview
20/66
20
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];}
-(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.m
-
7/28/2019 Oc Overview
21/66
21
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 = [selfgetValue];
[self remove];
return ret;
}
@endstack.h stack.m
-
7/28/2019 Oc Overview
22/66
22
Example: main.c
#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;
}
$ gcc -x objective-c node.m linkList.m stack.m main.c -frameworkCocoa -o stackTest
$./stackTest
2 3 1
main.c
-
7/28/2019 Oc Overview
23/66
23
C and Objective-C
Programming
-
7/28/2019 Oc Overview
24/66
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 writingOS code
But,.
Memory management responsibility Explicit initialization and error detection
More room for mistakes
-
7/28/2019 Oc Overview
25/66
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 madeby beginners
so that you get your homework done quickly
You can write more complicated code
-
7/28/2019 Oc Overview
26/66
26
Simple Example
#include
void main(void){
printf(Hello World. \n \t and you ! \n );/* print out a message */
return;}
$Hello World.
and you !
$
-
7/28/2019 Oc Overview
27/66
27
Summarizing the Example
#include = include header file stdio.hNo semicolon at end
Small letters onlyC 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 withinprintf.
printf(Have you heard of \The Rock\ ? \n);
Si l D t T
-
7/28/2019 Oc Overview
28/66
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:
E l !
-
7/28/2019 Oc Overview
29/66
29
#include
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.
$
Example !
T i
-
7/28/2019 Oc Overview
30/66
30
Type conversion#include void main(void)
{ int i,j = 12; /* i not initialized, only j */float f1,f2 = 1.2;
i = (int) f2; /* explicit: i
-
7/28/2019 Oc Overview
31/66
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
-
7/28/2019 Oc Overview
32/66
32
Example
#include #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
-
7/28/2019 Oc Overview
33/66
33
One-Dimensional Arrays
#include
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;}
-
7/28/2019 Oc Overview
34/66
34
More arrays
Stringschar 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 at program start
Multi-dimensional arraysint points[3][4];
points [1][3] = 12; /* NOT points[3,4] */printf(%d, points[1][3]);
-
7/28/2019 Oc Overview
35/66
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 characterchar name[6] = {C,S,4,1,4,\0};
/* \0= end of string */
printf(%s, name); /* print until \0 */
-
7/28/2019 Oc Overview
36/66
36
Memory layout and addresses
5 10 12.5 9. 8 c d
int x = 5, y = 10;float f = 12.5, g = 9.8;
char c = c, d = d;
4300 4304 4308 4312 4316 4317
Pointers made eas 1
-
7/28/2019 Oc Overview
37/66
37
Pointers made easy - 1
Pointer= variable containing address of another variablefloat f; /* data variable */
float *f_addr; /* pointer variable */
f_addr = &f; /* & = address operator */
? ?
f f_addr
4300 4304
?
any float
any address
? 4300
f f_addr
4300 4304
Pointers made easy 2
-
7/28/2019 Oc Overview
38/66
38
Pointers made easy - 2*f_addr = 3.2; /* indirection operator */
float g=*f_addr; /* indirection:g is now 3.2 */
f = 1.3;
f f_addr
4300 4304
3.2 4300
f f_addr
4300 4304
1.3 4300
Pointer Example
-
7/28/2019 Oc Overview
39/66
39
#include
void main(void) {int j;int *ptr;
ptr=&j; /* initialize ptr before using it *//* *ptr=4 does NOT initialize ptr */
*ptr=4; /* j
-
7/28/2019 Oc Overview
40/66
40
#include
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 */
}
Dynamic Memory allocation
Explicit allocation and de-allocation
Elementary file handling
-
7/28/2019 Oc Overview
41/66
41
Elementary file handling#include
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);
/* dont forget to close file handles */fclose(input_file);
return;
}
-
7/28/2019 Oc Overview
42/66
42
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
-
7/28/2019 Oc Overview
43/66
43
Functions - why and how ?
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 basic example
-
7/28/2019 Oc Overview
44/66
44
Functionsbasic example
#include 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 */
}
Arguments by reference
-
7/28/2019 Oc Overview
45/66
45
Arguments by reference
#include 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 */}
Why pointer arguments?!
-
7/28/2019 Oc Overview
46/66
46
Why pointer arguments?!
#include
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;
}
Why pointer arguments? This is why
-
7/28/2019 Oc Overview
47/66
47
Why pointer arguments? This is why
#include
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 byreference */
int temp;
temp = *n1;*n1 = *n2;*n2 = temp;
}
Whats wrong with this ?
-
7/28/2019 Oc Overview
48/66
48
What s wrong with this ?
#include
void dosomething(int *ptr);
main() {int *p;dosomething(p)
printf(%d, *p); /* will this work ? */}
void dosomething(int *ptr){ /* passed and returned byreference */
int temp=32+12;
ptr = &(temp);}
/* compiles correctly, but gives run-time error */
Passing and returning arrays
-
7/28/2019 Oc Overview
49/66
49
Passing and returning arrays
#include
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;
}
M l f
-
7/28/2019 Oc Overview
50/66
50
Memory layout of programs
Header info
Code
Data - Heap
0
100
400
560
1010
1200
Dynamic memory
Local memory+ function callstack
all normal vars
all malloc()s
Data - stack
-
7/28/2019 Oc Overview
51/66
51
Program with multiple files
Library headers
Standard
User-defined
void myproc(void);int mydata;
#include #include mypgm.h
void myproc(void){
mydata=2;. . . /* some code */}
#include #include mypgm.h
void main(void){
myproc();}
hw.c mypgm.c
mypgm.h
E
-
7/28/2019 Oc Overview
52/66
52
Externs#include
extern char user2line [20]; /* global variable definedin another file */
char user1line[30]; /* global for this file */void dummy(void);
void main(void) {char user1line[20]; /* different from earlier
user1line[30] */. . . /* restricted to this func */}
void dummy(){extern char user1line[]; /* the global user1line[30] */. . .}
-
7/28/2019 Oc Overview
53/66
More on Structures
-
7/28/2019 Oc Overview
54/66
54
More on Structuresstruct person{
char name[41];
int age;float height;struct { /* embedded structure */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;
Passing/Returning a structure
-
7/28/2019 Oc Overview
55/66
55
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 ? */
enum - enumerated data types
-
7/28/2019 Oc Overview
56/66
56
enum - enumerated data types
#include enum month{
JANUARY, /* like #define JANUARY 0 */FEBRUARY, /* like #define FEBRUARY 1 */
MARCH /* */};
/* JANUARY is the same as month.JANUARY */
/* alternatively, . */
enum month{
JANUARY=1, /* like #define JANUARY 1 */FEBRUARY, /* like #define FEBRUARY 2 */
MARCH /* */};
Synonym for a data type
-
7/28/2019 Oc Overview
57/66
57
typedef int Employees;
Employees my_company; /* same as int my_company; */
typedef struct person Person;
Person me; /* same as struct person me; */
typedef struct person *Personptr;
Personptr ptrtome; /* same as struct person *ptrtome;*/
Synonym for a data type
Easier to remember
Clean code
M i t
-
7/28/2019 Oc Overview
58/66
58
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
-
7/28/2019 Oc Overview
59/66
59
2-D arrays
2-dimensional arrayint weekends[52][2];
weekends
weekends[2][1] is same as *(weekends+2*2+1) NOT *weekends+2*2+1 :this is an int !
[0][0] [0][1] [1][0] [1][1] [2][0] [2][1] [3][0] . . . .
Pointer Example - argc and argv
-
7/28/2019 Oc Overview
60/66
60
#include /* program called with cmd line parameters */
void main(int argc, char *argv[]) {
int ctr;
for (ctr = 0; ctr < argc; ctr = ctr + 1) {printf(Argument #%d is -> |%s|\n, ctr, argv[ctr]);} /* ex., argv[0] == the name of the program */
}
Pointer Example argc and argv
parameters
Strings
-
7/28/2019 Oc Overview
61/66
61
Strings
#include
main() {char msg[10]; /* array of 10 chars */char *p; /* pointer to a char */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 */
}
-
7/28/2019 Oc Overview
62/66
62
Pointer to function
Advantage ? more flexibility
int func(); /*function returning integer*/
int *func(); /*function returning pointer to integer*/int (*func)(); /*pointer to function returning integer*/int *(*func)(); /*pointer to func returning ptr to int*/
Pointer to function - Example
-
7/28/2019 Oc Overview
63/66
63
Pointer to function Example
#include
void myproc (int d);void mycaller(void (* f)(int), int param);
void main(void) {myproc(10); /* call myproc with parameter 10*/
mycaller(myproc, 10); /* and do the same again ! */}
void mycaller(void (* f)(int), int param){(*f)(param); /* call function *f with param */
}
void myproc (int d){. . . /* do something with d */
}
Doing more complicated things
-
7/28/2019 Oc Overview
64/66
64
Doing more complicated things
To declare an array of N pointers to functions returning
pointers to functions returning pointers to characters
1. char *(*(*a[N])())();
2. Build the declaration up in stages, using typedefs:
typedef char *pc; /* pointer to char */typedef pc fpc(); /* function returning pointer to char */typedef fpc *pfpc; /* pointer to above */typedef pfpc fpfpc(); /* function returning... */typedef fpfpc *pfpfpc; /* pointer to... */pfpfpc a[N]; /* array of... */
-
7/28/2019 Oc Overview
65/66
65
Before you go onto Objective-C
Always initialize anything before using it (especiallypointers)
Dont use pointers after freeing them
Dont return a functions local variables by reference
No exceptionsso check for errors everywhere
An array is also a pointer, but its value is immutable.
f
-
7/28/2019 Oc Overview
66/66
References
Cox, Brad. Object Oriented Programming: anEvolutioary Approach
Sebesta, Robert. Concepts of ProgrammingLanguages
Apple Inc. Apple Developer Connectionhttp://developer.apple.com
Stevenson, Scott. Theocacaohttp://theocacao.com/document.page/510