SlideShare une entreprise Scribd logo
1  sur  94
Télécharger pour lire hors ligne
Introduc)on	
  to	
  Objec)ve-­‐C	
  
Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
QUICKSTART	
  
Background	
  
•  Objec)ve-­‐C	
  is	
  layered	
  on	
  top	
  of	
  the	
  C	
  –	
  
language	
  
– Based	
  on	
  SmallTalk-­‐80	
  
– Designed	
  in	
  early	
  1980s	
  
•  NeXT	
  SoLware	
  licensed	
  Objec)ve-­‐C	
  in	
  1988	
  
•  Apple	
  Computer	
  acquired	
  NeXT	
  in	
  1996	
  
•  Today:	
  na)ve	
  language	
  for	
  developing	
  Mac	
  OS	
  
X	
  -­‐	
  and	
  iPhone	
  -­‐	
  apps	
  
Class	
  Declara)on:	
  MyPoint.h
Class	
  Implementa)on:	
  MyPoint.m
Test	
  the	
  Class:	
  main.m
Simple	
  makefile	
  
MyPoint : MyPoint.m main.m
clang -fno-objc-arc -framework foundation
MyPoint.m main.m -o MyPoint
run :
./MyPoint
clean :
rm MyPoint
Compiling	
  and	
  Running	
  
TB308POHJUS-L-2:point pohjus$ ls -al
total 32
drwxr-xr-x 6 pohjus staff 204 18 Tou 15:32 .
drwxr-xr-x 3 pohjus staff 102 18 Tou 14:52 ..
-rw-r--r--@ 1 pohjus staff 196 18 Tou 15:25 MyPoint.h
-rw-r--r--@ 1 pohjus staff 268 18 Tou 15:23 MyPoint.m
-rw-r--r--@ 1 pohjus staff 339 18 Tou 15:25 main.m
-rw-r--r--@ 1 pohjus staff 120 18 Tou 15:14 makefile
TB308POHJUS-L-2:point pohjus$ make
clang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPoint
TB308POHJUS-L-2:point pohjus$ make run
./MyPoint
2009-05-18 15:32:46.339 MyPoint[8725:807] X = 0 and Y = 0
2009-05-18 15:32:46.341 MyPoint[8725:807] X = 8 and Y = 7
TB308POHJUS-L-2:point pohjus$
Instan)a)ng	
  an	
  Object	
  
// Declare a pointer to the object
MyPoint* point;
// Allocate memory for the object
point = [MyPoint alloc];
// Initialize the object
point = [point init];
Instan)a)ng	
  an	
  Object:	
  One	
  Liner	
  
// Allocate and initialize the object
MyPoint* point1 = [[MyPoint alloc] init];
Messages	
  (Methods)	
  
- (void) setX: (int) n;!
method	
  type:	
  
+	
  =	
  class	
  method	
  
-­‐	
  =	
  object	
  method	
  
return	
  type	
   selector	
  name	
  
	
  
argument	
  type	
  
	
  
argument	
  
name	
  
	
  
Messages,	
  with	
  Two	
  Arguments	
  
Declara=on	
  
- (void) setXAndY: (int) x: (int) y
Usage	
  
[object setXAndY: 5: 6];
Declara=on,	
  be@er	
  way	
  
- (void) setX: (int) x andY: (int) y
Usage	
  
[object setX: 5 andY: 6];
EXERCISES	
  
MEMORY	
  MANAGEMENT	
  AND	
  OBJECT	
  
LIFECYCLE	
  
	
  
Memory	
  Handling	
  in	
  General	
  
•  When	
  allocate	
  something	
  it	
  must	
  be	
  released	
  
– Memory	
  consump)on	
  
•  In	
  Java,	
  garbage	
  collector	
  takes	
  care	
  of	
  the	
  
release.	
  Separate	
  thread	
  looking	
  for	
  objects	
  
that	
  can	
  be	
  released	
  
•  In	
  Obj-­‐C	
  and	
  C/C++,	
  programmer	
  is	
  
responsible	
  about	
  the	
  release.	
  
About	
  Pointers	
  
•  int	
  a	
  =	
  5;	
  
– Holds	
  one	
  integer	
  value	
  
– The	
  integer	
  is	
  stored	
  in	
  some	
  memory	
  address	
  
•  Where?	
  
– You	
  can	
  get	
  the	
  memory	
  address	
  by	
  using	
  &	
  in	
  
front	
  of	
  the	
  variable:	
  &a	
  
Example	
  of	
  Memory	
  Address	
  
int main(int argc, char *argv[])
{
int a = 5;
// prints 5
NSLog(@"%i", a);
// prints something like 0x7fff5fbff9cc
NSLog(@"%p", &a);
return 0;
}
Pointers	
  
•  Pointer	
  is	
  a	
  variable	
  that	
  stores	
  memory	
  
address	
  
•  int	
  a;	
  
– holds	
  integer	
  variable	
  
•  int*	
  b;	
  
– holds	
  memory	
  address	
  that	
  points	
  to	
  integer	
  value	
  
•  int*	
  b	
  =	
  &a;	
  
– Now	
  b	
  has	
  the	
  memory	
  address	
  of	
  a	
  
Example	
  about	
  Pointers	
  
#import "MyPoint.h"
int main(int argc, char *argv[])
{
int a = 5;
// Store a's memory address to variable b
int *b = &a;
// prints 5
NSLog(@"%i", a);
// prints something like 0x7fff5fbff9cc
NSLog(@"%p", &a);
// prints something like 0x7fff5fbff9cc
NSLog(@"%p", b);
// prints 5
NSLog(@"%i", *b);
return 0;
}
What	
  is	
  the	
  result	
  now?	
  
int main(int argc, char *argv[])
{
int a = 5;
// Store a's memory address to variable b
int *b = &a;
if(b == &a)
{
NSLog(@"Do we go here?");
}
if(*b == a)
{
NSLog(@"What about here?");
}
return 0;
}
What	
  is	
  the	
  result	
  now?	
  
int main(int argc, char *argv[])
{
int a = 5;
int *b = &a;
*b = 10;
NSLog(@"%i", a);
return 0;
}
Memory	
  Areas	
  
•  Memory	
  can	
  be	
  divided	
  into	
  three	
  categories	
  
1.  Global	
  or	
  sta)c	
  
2.  Stack	
  
3.  Heap	
  
Sta)c	
  
•  When	
  something	
  is	
  in	
  sta)c	
  memory,	
  it's	
  there	
  
all	
  the	
  )me	
  when	
  app	
  is	
  running	
  
•  So	
  when	
  star)ng	
  the	
  app,	
  the	
  memory	
  is	
  
allocated	
  an	
  when	
  the	
  app	
  closes,	
  the	
  memory	
  
is	
  deallocated	
  
•  The	
  variable	
  is	
  stored	
  in	
  the	
  same	
  memory	
  
address	
  all	
  the	
  )me.	
  
Example	
  of	
  Sta)c	
  Memory	
  
int thisIsStoredInStaticMemory = 5;
int main(int argc, char *argv[])
{
static int thisIsAlsoStoredInStaticMemory = 10;
NSLog(@"My number = %i", thisIsStoredInStaticMemory);
NSLog(@"My number = %i", thisIsAlsoStoredInStaticMemory);
return 0;
}
Stack	
  -­‐	
  Memory	
  
•  Stack	
  –	
  memoryarea	
  is	
  usually	
  small	
  
•  If	
  you	
  put	
  too	
  much	
  "stuff"	
  into	
  stack,	
  you	
  
might	
  get	
  stack	
  overflow	
  
•  Local	
  variables	
  are	
  stored	
  in	
  stack!	
  
•  Variables	
  are	
  released	
  when	
  out	
  of	
  scope	
  
Example	
  of	
  Stack	
  Memory	
  
int main(int argc, char *argv[])
{
int stack1 = 3;
NSLog(@"My number = %i", stack1);
if(YES)
{
int stack2 = 4;
NSLog(@"My number = %i", stack2);
// stack2 is released from memory now.
}
// stack1 is released from memory now.
return 0;
}
Example	
  of	
  Stack	
  Memory	
  
int main(int argc, char *argv[])
{
if(YES)
{
int stack2 = 4;
}
// Does this work?
NSLog(@"My number = %i", stack2);
return 0;
}
Heap	
  -­‐	
  Memory	
  
•  Heap	
  –	
  memory	
  is	
  the	
  large	
  memory	
  area	
  
where	
  almost	
  all	
  of	
  the	
  objects	
  go.	
  
•  Programmer	
  is	
  responsible	
  for	
  releasing	
  the	
  
objects!	
  	
  
Example	
  of	
  Heap	
  -­‐	
  memory	
  
#import "MyPoint.h"
int main(int argc, char *argv[])
{
MyPoint* point = [MyPoint alloc];
//...
[point release];
return 0;
}
Crea)ng	
  a	
  Object	
  
•  The	
  crea)on	
  of	
  an	
  object	
  is	
  done	
  in	
  two	
  parts	
  
•  1)	
  Alloca)ng	
  memory	
  
–  MyPoint* point = [MyPoint alloc];
•  2)	
  Ini)alize	
  object	
  state	
  
–  point = [point init];
•  Combined	
  
–  MyPoint* point = [[MyPoint alloc] init];
•  ó	
  
–  MyPoint* point = [MyPoint new];
What	
  happens	
  in	
  Memory?	
  
•  What	
  happens	
  in	
  here?	
  
– MyPoint* p = [MyPoint alloc];
•  Two	
  things!	
  
– MyPoint* p;
– p = [MyPoint alloc];
•  p	
  is	
  in	
  stack	
  –	
  memory!	
  
•  MyPoint	
  object	
  is	
  in	
  heap	
  memory!	
  
Problem?	
  
#import "MyPoint.h"
int main(int argc, char *argv[])
{
if(YES)
{
MyPoint* point = [MyPoint alloc];
}
[point release];
return 0;
}
Problem?	
  
#import "MyPoint.h"
int main(int argc, char *argv[])
{
MyPoint* point = [MyPoint alloc];
point = [MyPoint alloc];
[point release];
return 0;
}
init-­‐method?	
  
•  init-­‐method	
  is	
  implemented	
  in	
  NSObject
•  You	
  can	
  however	
  implement	
  your	
  own	
  init-­‐
method	
  
- (id) initWithName: (NSString*) aName
{
if(self = [super init])
{
name = aName;
}
return self;
}
Other	
  init-­‐methods	
  
•  Like	
  in	
  Java	
  and	
  C++,	
  one	
  can	
  have	
  mul)ple	
  
constructors	
  
•  In	
  Obj-­‐C,	
  one	
  can	
  have	
  mul)ple	
  init-­‐methods	
  
-  (id) init
-  (id) initWithX: (int) aX;
-  (id) initWithX: (int) aX andY: (int) aY
Deallocing	
  Object	
  and	
  Reference	
  Count	
  
•  Rules	
  about	
  reference	
  coun=ng	
  
–  When	
  object	
  is	
  created	
  its	
  reference	
  count	
  is	
  set	
  to	
  1	
  
–  Incremen)ng	
  the	
  reference	
  count:	
  
•  [point retain];
–  Decreasing	
  reference	
  count	
  
•  [point release];
–  When	
  reference	
  count	
  reaches	
  to	
  0,	
  dealloca=ng	
  occurs	
  
•  ARC	
  will	
  save	
  you	
  from	
  this!	
  
Reference	
  Count	
  Example	
  
#import <Foundation/Foundation.h>
@interface Cat : NSObject
{
}
- (void) printMyRetainCount;
@end
@implementation Cat
- (void) printMyRetainCount
{
NSLog(@"Retain count = %i", [self retainCount]);
}
@end
Reference	
  Count	
  Example	
  
int main(int argc, char *argv[])
{
Cat* myCat = [[Cat alloc] init];
[myCat printMyRetainCount]; // Retain count = 1
Cat* reference = myCat;
[reference retain];
[myCat printMyRetainCount]; // Retain count = 2
[myCat release];
[myCat printMyRetainCount]; // Retain count = 1
[myCat release]; // Deallocation
return 0;
}
dealloc
•  You	
  can	
  implement	
  a	
  dealloc	
  method	
  
(void) dealloc
{
// Some code
[super dealloc];
}
Reference	
  Count	
  Example	
  
#import <Foundation/Foundation.h>
@interface Cat : NSObject
{
NSString* name;
}
- (void) setName: (NSString *) theName
@end
@implementation Cat
- (void) setName: (NSString *) theName
{
name = theName;
}
@end
int main(int argc, char *argv[])
{
....
Cat* mirri = [[Cat alloc] init];
[mirri setName: someName];
// What happens now?
[someName release];
}
Since	
  reference	
  count	
  is	
  
0,	
  dealloca)on	
  occurs.	
  
This	
  means,	
  that	
  the	
  Cat	
  
does	
  not	
  have	
  a	
  name	
  
anymore.	
  
Reference	
  Count	
  Example	
  
#import <Foundation/Foundation.h>
@interface Cat : NSObject
{
NSString* name;
}
- (void) setName: (NSString *) theName
@end
@implementation Cat
- (void) setName: (NSString *) theName
{
[name release];
name = theName;
[name retain];
}
@end
int main(int argc, char *argv[])
{
....
Cat* mirri = [[Cat alloc] init];
[mirri setName: someName];
// What happens now?
[someName release];
}
Since	
  reference	
  count	
  is	
  
1,	
  dealloca)on	
  does	
  not	
  
occur	
  and	
  the	
  Cat	
  s)ll	
  
has	
  it's	
  name.	
  
Copying	
  a	
  Object	
  
- (void)setName:(NSString *)theName
}
[name release];
name = [theName copy];
}
Autorelease	
  Pool	
  
•  Every	
  Founda)on	
  program	
  must	
  set	
  up	
  
autorelease	
  pool	
  for	
  the	
  Founda)on	
  objects	
  
•  Pool	
  keeps	
  track	
  of	
  your	
  objects	
  for	
  later	
  
release	
  
–  NSAutoreleasePool *pool = [[NSAutoreleasePool
alloc] init];
–  ...
–  [pool drain];
Method	
  Names	
  
•  If	
  method	
  name	
  includes	
  alloc	
  or	
  copy,	
  it	
  
returns	
  a	
  object	
  that	
  must	
  be	
  released	
  
–  // Must be released
–  NSObject* object = [[NSObject alloc] init];
–  // Must be released
–  NSObject* copy = [object copy];
–  // Do not have to release
–  NSMutableString* string = [NSMutableString string];
•  The	
  above	
  string	
  is	
  released	
  in	
  Autorelease	
  Pool!
Problem	
  
// Programmer A code
[[someObject giveCat] eat];
// Programmer B code
- (Cat*) giveCat
{
// Must be released!
Cat* myCat = [[Cat alloc] init];
// But where? Should the programmer who calls this method be
// responsible for deallocation of the Cat? How does the programmer
// know this?
return myCat;
}
..
Solu)on	
  
// Programmer A code
[[someObject giveCat] eat];
// Programmer B code
- (Cat*) giveCat
{
// Must be released!
Cat* myCat = [[Cat alloc] init];
// But where? When autopool is drained!
[myCat autorelease];
return myCat;
}
Delayed	
  Release	
  
•  Autorelease	
  means	
  "send	
  release	
  message	
  
later".	
  
•  Release	
  message	
  is	
  sent	
  when	
  Autorelease	
  
Pool	
  is	
  released	
  
•  Autorelease	
  Pool	
  is	
  created	
  and	
  released	
  in	
  
UIKit	
  programs	
  automa=cally!	
  
– Pool	
  is	
  created	
  at	
  the	
  beginning	
  of	
  an	
  event	
  cycle	
  
– Pool	
  is	
  released	
  at	
  the	
  end	
  of	
  an	
  event	
  cycle	
  
Autorelease	
  Pools	
  
App	
  Loaded	
   Wait	
  for	
  Event	
   Handle	
  event	
   Exit	
  app	
  
Event	
  loop	
  
Pool	
  
created	
  
Pool	
  
released	
  
Autorelease	
  Pool	
  Usage	
  
// Method
- (Cat*) giveCat
{
// Must be released!
Cat* myCat = [[Cat alloc] init];
// But where? When autopool is drained!
[myCat autorelease];
return myCat;
}
// Usage
Cat* someCat = [object giveCat];
// someCat will be released in some time, so if you want to hold it, use
// retain
[someCat retain];
Rules	
  
•  If	
  method	
  name	
  contains	
  "alloc",	
  "new"	
  or	
  
"copy",	
  you	
  must	
  remember	
  to	
  use	
  release
or	
  autorelease
– Example:	
  alloc, newObject, mutableCopy
•  If	
  you	
  retain something,	
  you	
  must	
  use	
  
release or	
  autorelease
•  Instance	
  Variables:	
  retain	
  or	
  copy	
  
•  autorelease	
  means	
  "send	
  release later"	
  
Cat.h	
  
#import <Foundation/Foundation.h>
@interface Cat : NSObject
{
@private
NSString* name;
}
- (id) initWithName: (NSString*) aName;
- (void) setName: (NSString*) aName;
- (NSString*) getName;
- (void) dealloc;
@end
Cat.m	
  
#import "Cat.h"
@implementation Cat
- (id) initWithName: (NSString*) aName
{
if(self = [super init])
{
[self setName: aName];
}
return self;
}
- (NSString*) getName
{
return name;
}
- (void) setName: (NSString*) aName
{
if(aName != name)
{
[name release];
name = aName;
[name retain];
}
}
- (void) dealloc
{
[name release];
[super dealloc];
}
@end
main.m	
  
#import "Cat.h"
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool =
[[NSAutoreleasePool alloc] init];
// Create the string
NSString* catName = [[NSString
alloc] initWithString: @"Jack"];
// Create cat with the string
Cat* cat = [[Cat alloc]
initWithName: catName];
// Just testing. This does not
deallocate catName!
[catName release];
// Get the name
NSString* name = [cat getName];
// Print the name
NSLog(name);
// Release name and cat
[cat release];
[pool drain];
return 0;
}	
  
MANAGING	
  MEMORY	
  WITH	
  ARC	
  
ARC	
  to	
  the	
  rescue!	
  
ARC?	
  
•  ARC	
  (Automa=c	
  Reference	
  Coun=ng)	
  
– Compiler	
  does	
  automa/c	
  reference	
  coun/ng	
  by	
  
examining	
  the	
  source	
  code	
  and	
  then	
  add	
  the	
  
retain	
  and	
  release	
  messages	
  to	
  objects	
  
•  Not	
  garbage	
  collec)on,	
  no	
  background	
  
process	
  of	
  dealloca)on	
  of	
  objects!	
  
•  Inserts	
  retain	
  and	
  release	
  statements	
  based	
  
on	
  some	
  fixed	
  rules	
  
•  OS	
  X	
  10.7	
  and	
  iOS	
  5	
  for	
  all	
  features	
  
Object	
  lose	
  owners	
  
// Scenario 1
Person* jack = [[Person alloc] init];
jack = [[Person alloc] init];
// Scenario 2
Person* tina = [[Person alloc] init];
tina = nil;
// Scenario 3
if(yes) {
Person* dave = [[Person alloc] init];
}
Some	
  Fixed	
  rules	
  
•  If	
  object	
  is	
  allocated	
  and	
  local	
  to	
  method,	
  
release	
  statement	
  is	
  added	
  near	
  the	
  end	
  of	
  
that	
  method	
  
•  If	
  allocated	
  object	
  is	
  class	
  a@ribute,	
  release	
  is	
  
added	
  to	
  dealloc	
  
•  If	
  the	
  object	
  is	
  return	
  value,	
  it	
  gets	
  an	
  
autorelease	
  statement	
  
Guidelines	
  
•  Don’t	
  call!	
  
– retain, release, retainCount, autorelease
or dealloc
•  You	
  must	
  use	
  @autoreleasepool	
  syntax	
  
•  You	
  must	
  enable	
  ARC	
  
– clang -fobjc-arc -framework foundation
Car.m Motor.m main.m -o App
makefile	
  
MyPoint : Car.m Motor.m main.m
clang -fobjc-arc -framework foundation Car.m Motor.m main.m
-o App
run :
./App
clean :
rm App
main.m	
  
motor.h	
  
motor.m	
  
car.h	
  
car.m	
  
PROPERTIES	
  
Objec)ve-­‐C	
  2.0:	
  @property
Objec)ve-­‐C	
  2.0:	
  @synthesize
Objec)ve-­‐C	
  2.0:	
  Dot	
  Syntax	
  
Autosynthesize	
  
Autosynthesize	
  
Property	
  Declara)on	
  Aoributes:	
  
Writability	
  
•  You	
  can	
  decorate	
  a	
  property	
  with	
  aoributes,	
  
example:	
  
– @property (readonly) int x;
•  readwrite
– Indicates	
  that	
  the	
  property	
  is	
  read/write.	
  Default	
  
•  readonly
– Only	
  read	
  
– Generates	
  only	
  geoer	
  method	
  
Seoer	
  Seman)cs	
  
•  assign
–  Simple	
  seoer.	
  Default.	
  
•  weak
–  Non-­‐owning	
  rela)onship	
  with	
  an	
  object	
  
–  If	
  object	
  is	
  deallocated,	
  the	
  property	
  is	
  set	
  to	
  nil	
  
•  strong
–  Owning	
  rela)onship	
  with	
  an	
  object	
  
•  copy
–  Specifies	
  that	
  a	
  copy	
  of	
  the	
  object	
  should	
  be	
  used	
  for	
  
assignment	
  
Seoer	
  Seman)cs	
  Examples	
  
// assign
property = newValue;
// copy
if (property != newValue)
{
[property release];
property = [newValue copy];
}
Atomicity	
  
•  nonatomic
– Specifies	
  that	
  accessor	
  are	
  non-­‐atomic.	
  	
  
•  Proper)es	
  are	
  atomic	
  by	
  default:	
  
– [_internal lock];
– id result = [[value retain] autorelease];
– [_internal unlock];
– return id;
Car.h	
  
Motor.h	
  
Main.m	
  
Change!	
  Car.h	
  
STRINGS	
  
About	
  Strings	
  
•  C	
  String	
  
– char * // Array of characters
•  NSString
– Object,	
  that	
  holds	
  array	
  of	
  Unicode	
  characters	
  
– Is	
  immutable,	
  contents	
  cannot	
  be	
  changed	
  
aLerwards!	
  
•  NSMutableString
– String	
  that	
  can	
  be	
  modified	
  aLerwards	
  
Crea)ng	
  Strings	
  
// Simple way
NSString *temp1 = @"Hello World!";
// Appending, notice that this produces new string
NSString *beginning = @"beginning";
NSString *alphaAndOmega = [beginning
stringByAppendingString:@" and end"];
Formapng	
  
•  Formapng	
  
–  NSString *string1 = [NSString stringWithFormat:@"A
string: %@, a float: %1.2f", @"string", 31415.9265];
–  // string1 is "A string: string, a float: 31415.93"
•  Format	
  Specifiers?	
  
– http://developer.apple.com/iphone/
library/documentation/Cocoa/Conceptual/
Strings/Articles/formatSpecifiers.html#//
apple_ref/doc/uid/TP40004265-SW1
NSString	
  methods	
  
•  See:	
  
– http://developer.apple.com/documentation/
Cocoa/Reference/Foundation/Classes/
NSString_Class/Reference/NSString.html
NSMutableString methods	
  
•  NSMutableString inherites	
  NSString
•  With	
  NSMutableString you	
  can	
  modify	
  the	
  
string	
  with	
  these	
  methods	
  
– appendFormat:
– appendString:
– deleteCharactersInRange:
– insertString:atIndex:
– replaceCharactersInRange:withString:
– replaceOccurrencesOfString:withString:options:range:
– setString:
PROTOCOLS	
  
Protocols?	
  
•  Compared	
  to	
  Java,	
  protocols	
  are	
  interfaces	
  
•  You	
  define	
  methods	
  that	
  some	
  object	
  must	
  
implement	
  
	
  
	
  
Using	
  Protocols	
  
// MyProtocolName.h
// Notice that the protocol inherites NSObject
// protocol!
@protocol MyProtocolName <NSObject>
//Method declarations go here
@end
// MyObject
@interface Class: NSObject <MyProtocolName>
	
  
Protocol	
  as	
  Variable	
  
•  In	
  Java	
  
–  MyInterface object = new MyObject();
•  In	
  Obj-­‐C	
  
–  id<MyProtocolName> object = [[MyObject
alloc] init];
•  As	
  a	
  method	
  argument	
  
–  (void) doSomethingWithThisObject:
(id<MyProtocolName>) aObject
•  ID	
  is	
  a	
  predefined	
  pointer	
  type	
  for	
  an	
  arbitrary	
  
object	
  
	
  
FOUNDATION	
  CLASSES	
  
NSObject	
  
•  NSObject	
  is	
  the	
  root	
  class	
  of	
  Most	
  Obj-­‐C	
  
classes	
  
•  Crea)ng,	
  copying,	
  dealloca)ng	
  objects	
  
	
  
Collec)ons	
  
•  Array:	
  Ordered	
  Collec/ons	
  
•  Dic)onary:	
  Collec/ons	
  of	
  Keys	
  and	
  Values	
  
•  Set:	
  Unordered	
  Collec/ons	
  of	
  Objects	
  
•  Counted	
  Sets:	
  Unordered	
  Collec/on	
  of	
  
Indis/nct	
  Objects	
  
•  Enumera)on:	
  Traversing	
  a	
  Collec/on's	
  
Elements	
  
•  Mutable	
  and	
  immutable	
  versions!	
  
Other	
  Classes	
  
•  NSNumber,	
  wrapper	
  for	
  standard	
  number	
  
types	
  
•  NSDate,	
  NSCalendarDate	
  

Contenu connexe

Tendances

"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)AvitoTech
 
Opaque Pointers Are Coming
Opaque Pointers Are ComingOpaque Pointers Are Coming
Opaque Pointers Are ComingNikita Popov
 
PyTorch crash course
PyTorch crash coursePyTorch crash course
PyTorch crash courseNader Karimi
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow규영 허
 
Intel JIT Talk
Intel JIT TalkIntel JIT Talk
Intel JIT Talkiamdvander
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Jan Wedekind
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Databricks
 
Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Mark Rees
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 

Tendances (20)

"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
"О некоторых особенностях Objective-C++" Влад Михайленко (Maps.Me)
 
Ontopia tutorial
Ontopia tutorialOntopia tutorial
Ontopia tutorial
 
Opaque Pointers Are Coming
Opaque Pointers Are ComingOpaque Pointers Are Coming
Opaque Pointers Are Coming
 
PyTorch crash course
PyTorch crash coursePyTorch crash course
PyTorch crash course
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Lecture1 classes2
Lecture1 classes2Lecture1 classes2
Lecture1 classes2
 
Intel JIT Talk
Intel JIT TalkIntel JIT Talk
Intel JIT Talk
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0
 
Manual specialization
Manual specializationManual specialization
Manual specialization
 
Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 

Similaire à Introduction to objective c

Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - CJussi Pohjolainen
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Saket Pathak
 
LCDS - State Presentation
LCDS - State PresentationLCDS - State Presentation
LCDS - State PresentationRuochun Tzeng
 
(2) collections algorithms
(2) collections algorithms(2) collections algorithms
(2) collections algorithmsNico Ludwig
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++Mohammad Shaker
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Yung-Yu Chen
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation웅식 전
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)David de Boer
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming languageKumar Gaurav
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたTaro Matsuzawa
 

Similaire à Introduction to objective c (20)

Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
LCDS - State Presentation
LCDS - State PresentationLCDS - State Presentation
LCDS - State Presentation
 
(2) collections algorithms
(2) collections algorithms(2) collections algorithms
(2) collections algorithms
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 
13. dynamic allocation
13. dynamic allocation13. dynamic allocation
13. dynamic allocation
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
DIY Java Profiling
DIY Java ProfilingDIY Java Profiling
DIY Java Profiling
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
 

Plus de sagaroceanic11

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reportssagaroceanic11
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensicssagaroceanic11
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimessagaroceanic11
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attackssagaroceanic11
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attackssagaroceanic11
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidencesagaroceanic11
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computerssagaroceanic11
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays worldsagaroceanic11
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mwaresagaroceanic11
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overviewsagaroceanic11
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisationsagaroceanic11
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecyclesagaroceanic11
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3sagaroceanic11
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overviewsagaroceanic11
 

Plus de sagaroceanic11 (20)

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reports
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensics
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimes
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attacks
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attacks
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidence
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computers
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays world
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mware
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overview
 
Virtualisation basics
Virtualisation basicsVirtualisation basics
Virtualisation basics
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisation
 
6 service operation
6 service operation6 service operation
6 service operation
 
5 service transition
5 service transition5 service transition
5 service transition
 
4 service design
4 service design4 service design
4 service design
 
3 service strategy
3 service strategy3 service strategy
3 service strategy
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecycle
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 

Dernier

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Dernier (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Introduction to objective c

  • 1. Introduc)on  to  Objec)ve-­‐C   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 3. Background   •  Objec)ve-­‐C  is  layered  on  top  of  the  C  –   language   – Based  on  SmallTalk-­‐80   – Designed  in  early  1980s   •  NeXT  SoLware  licensed  Objec)ve-­‐C  in  1988   •  Apple  Computer  acquired  NeXT  in  1996   •  Today:  na)ve  language  for  developing  Mac  OS   X  -­‐  and  iPhone  -­‐  apps  
  • 7. Simple  makefile   MyPoint : MyPoint.m main.m clang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPoint run : ./MyPoint clean : rm MyPoint
  • 8. Compiling  and  Running   TB308POHJUS-L-2:point pohjus$ ls -al total 32 drwxr-xr-x 6 pohjus staff 204 18 Tou 15:32 . drwxr-xr-x 3 pohjus staff 102 18 Tou 14:52 .. -rw-r--r--@ 1 pohjus staff 196 18 Tou 15:25 MyPoint.h -rw-r--r--@ 1 pohjus staff 268 18 Tou 15:23 MyPoint.m -rw-r--r--@ 1 pohjus staff 339 18 Tou 15:25 main.m -rw-r--r--@ 1 pohjus staff 120 18 Tou 15:14 makefile TB308POHJUS-L-2:point pohjus$ make clang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPoint TB308POHJUS-L-2:point pohjus$ make run ./MyPoint 2009-05-18 15:32:46.339 MyPoint[8725:807] X = 0 and Y = 0 2009-05-18 15:32:46.341 MyPoint[8725:807] X = 8 and Y = 7 TB308POHJUS-L-2:point pohjus$
  • 9. Instan)a)ng  an  Object   // Declare a pointer to the object MyPoint* point; // Allocate memory for the object point = [MyPoint alloc]; // Initialize the object point = [point init];
  • 10. Instan)a)ng  an  Object:  One  Liner   // Allocate and initialize the object MyPoint* point1 = [[MyPoint alloc] init];
  • 11. Messages  (Methods)   - (void) setX: (int) n;! method  type:   +  =  class  method   -­‐  =  object  method   return  type   selector  name     argument  type     argument   name    
  • 12. Messages,  with  Two  Arguments   Declara=on   - (void) setXAndY: (int) x: (int) y Usage   [object setXAndY: 5: 6]; Declara=on,  be@er  way   - (void) setX: (int) x andY: (int) y Usage   [object setX: 5 andY: 6];
  • 14. MEMORY  MANAGEMENT  AND  OBJECT   LIFECYCLE    
  • 15. Memory  Handling  in  General   •  When  allocate  something  it  must  be  released   – Memory  consump)on   •  In  Java,  garbage  collector  takes  care  of  the   release.  Separate  thread  looking  for  objects   that  can  be  released   •  In  Obj-­‐C  and  C/C++,  programmer  is   responsible  about  the  release.  
  • 16. About  Pointers   •  int  a  =  5;   – Holds  one  integer  value   – The  integer  is  stored  in  some  memory  address   •  Where?   – You  can  get  the  memory  address  by  using  &  in   front  of  the  variable:  &a  
  • 17. Example  of  Memory  Address   int main(int argc, char *argv[]) { int a = 5; // prints 5 NSLog(@"%i", a); // prints something like 0x7fff5fbff9cc NSLog(@"%p", &a); return 0; }
  • 18. Pointers   •  Pointer  is  a  variable  that  stores  memory   address   •  int  a;   – holds  integer  variable   •  int*  b;   – holds  memory  address  that  points  to  integer  value   •  int*  b  =  &a;   – Now  b  has  the  memory  address  of  a  
  • 19. Example  about  Pointers   #import "MyPoint.h" int main(int argc, char *argv[]) { int a = 5; // Store a's memory address to variable b int *b = &a; // prints 5 NSLog(@"%i", a); // prints something like 0x7fff5fbff9cc NSLog(@"%p", &a); // prints something like 0x7fff5fbff9cc NSLog(@"%p", b); // prints 5 NSLog(@"%i", *b); return 0; }
  • 20. What  is  the  result  now?   int main(int argc, char *argv[]) { int a = 5; // Store a's memory address to variable b int *b = &a; if(b == &a) { NSLog(@"Do we go here?"); } if(*b == a) { NSLog(@"What about here?"); } return 0; }
  • 21. What  is  the  result  now?   int main(int argc, char *argv[]) { int a = 5; int *b = &a; *b = 10; NSLog(@"%i", a); return 0; }
  • 22. Memory  Areas   •  Memory  can  be  divided  into  three  categories   1.  Global  or  sta)c   2.  Stack   3.  Heap  
  • 23. Sta)c   •  When  something  is  in  sta)c  memory,  it's  there   all  the  )me  when  app  is  running   •  So  when  star)ng  the  app,  the  memory  is   allocated  an  when  the  app  closes,  the  memory   is  deallocated   •  The  variable  is  stored  in  the  same  memory   address  all  the  )me.  
  • 24. Example  of  Sta)c  Memory   int thisIsStoredInStaticMemory = 5; int main(int argc, char *argv[]) { static int thisIsAlsoStoredInStaticMemory = 10; NSLog(@"My number = %i", thisIsStoredInStaticMemory); NSLog(@"My number = %i", thisIsAlsoStoredInStaticMemory); return 0; }
  • 25. Stack  -­‐  Memory   •  Stack  –  memoryarea  is  usually  small   •  If  you  put  too  much  "stuff"  into  stack,  you   might  get  stack  overflow   •  Local  variables  are  stored  in  stack!   •  Variables  are  released  when  out  of  scope  
  • 26. Example  of  Stack  Memory   int main(int argc, char *argv[]) { int stack1 = 3; NSLog(@"My number = %i", stack1); if(YES) { int stack2 = 4; NSLog(@"My number = %i", stack2); // stack2 is released from memory now. } // stack1 is released from memory now. return 0; }
  • 27. Example  of  Stack  Memory   int main(int argc, char *argv[]) { if(YES) { int stack2 = 4; } // Does this work? NSLog(@"My number = %i", stack2); return 0; }
  • 28. Heap  -­‐  Memory   •  Heap  –  memory  is  the  large  memory  area   where  almost  all  of  the  objects  go.   •  Programmer  is  responsible  for  releasing  the   objects!    
  • 29. Example  of  Heap  -­‐  memory   #import "MyPoint.h" int main(int argc, char *argv[]) { MyPoint* point = [MyPoint alloc]; //... [point release]; return 0; }
  • 30. Crea)ng  a  Object   •  The  crea)on  of  an  object  is  done  in  two  parts   •  1)  Alloca)ng  memory   –  MyPoint* point = [MyPoint alloc]; •  2)  Ini)alize  object  state   –  point = [point init]; •  Combined   –  MyPoint* point = [[MyPoint alloc] init]; •  ó   –  MyPoint* point = [MyPoint new];
  • 31. What  happens  in  Memory?   •  What  happens  in  here?   – MyPoint* p = [MyPoint alloc]; •  Two  things!   – MyPoint* p; – p = [MyPoint alloc]; •  p  is  in  stack  –  memory!   •  MyPoint  object  is  in  heap  memory!  
  • 32. Problem?   #import "MyPoint.h" int main(int argc, char *argv[]) { if(YES) { MyPoint* point = [MyPoint alloc]; } [point release]; return 0; }
  • 33. Problem?   #import "MyPoint.h" int main(int argc, char *argv[]) { MyPoint* point = [MyPoint alloc]; point = [MyPoint alloc]; [point release]; return 0; }
  • 34. init-­‐method?   •  init-­‐method  is  implemented  in  NSObject •  You  can  however  implement  your  own  init-­‐ method   - (id) initWithName: (NSString*) aName { if(self = [super init]) { name = aName; } return self; }
  • 35. Other  init-­‐methods   •  Like  in  Java  and  C++,  one  can  have  mul)ple   constructors   •  In  Obj-­‐C,  one  can  have  mul)ple  init-­‐methods   -  (id) init -  (id) initWithX: (int) aX; -  (id) initWithX: (int) aX andY: (int) aY
  • 36. Deallocing  Object  and  Reference  Count   •  Rules  about  reference  coun=ng   –  When  object  is  created  its  reference  count  is  set  to  1   –  Incremen)ng  the  reference  count:   •  [point retain]; –  Decreasing  reference  count   •  [point release]; –  When  reference  count  reaches  to  0,  dealloca=ng  occurs   •  ARC  will  save  you  from  this!  
  • 37. Reference  Count  Example   #import <Foundation/Foundation.h> @interface Cat : NSObject { } - (void) printMyRetainCount; @end @implementation Cat - (void) printMyRetainCount { NSLog(@"Retain count = %i", [self retainCount]); } @end
  • 38. Reference  Count  Example   int main(int argc, char *argv[]) { Cat* myCat = [[Cat alloc] init]; [myCat printMyRetainCount]; // Retain count = 1 Cat* reference = myCat; [reference retain]; [myCat printMyRetainCount]; // Retain count = 2 [myCat release]; [myCat printMyRetainCount]; // Retain count = 1 [myCat release]; // Deallocation return 0; }
  • 39. dealloc •  You  can  implement  a  dealloc  method   (void) dealloc { // Some code [super dealloc]; }
  • 40. Reference  Count  Example   #import <Foundation/Foundation.h> @interface Cat : NSObject { NSString* name; } - (void) setName: (NSString *) theName @end @implementation Cat - (void) setName: (NSString *) theName { name = theName; } @end int main(int argc, char *argv[]) { .... Cat* mirri = [[Cat alloc] init]; [mirri setName: someName]; // What happens now? [someName release]; } Since  reference  count  is   0,  dealloca)on  occurs.   This  means,  that  the  Cat   does  not  have  a  name   anymore.  
  • 41. Reference  Count  Example   #import <Foundation/Foundation.h> @interface Cat : NSObject { NSString* name; } - (void) setName: (NSString *) theName @end @implementation Cat - (void) setName: (NSString *) theName { [name release]; name = theName; [name retain]; } @end int main(int argc, char *argv[]) { .... Cat* mirri = [[Cat alloc] init]; [mirri setName: someName]; // What happens now? [someName release]; } Since  reference  count  is   1,  dealloca)on  does  not   occur  and  the  Cat  s)ll   has  it's  name.  
  • 42. Copying  a  Object   - (void)setName:(NSString *)theName } [name release]; name = [theName copy]; }
  • 43. Autorelease  Pool   •  Every  Founda)on  program  must  set  up   autorelease  pool  for  the  Founda)on  objects   •  Pool  keeps  track  of  your  objects  for  later   release   –  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; –  ... –  [pool drain];
  • 44. Method  Names   •  If  method  name  includes  alloc  or  copy,  it   returns  a  object  that  must  be  released   –  // Must be released –  NSObject* object = [[NSObject alloc] init]; –  // Must be released –  NSObject* copy = [object copy]; –  // Do not have to release –  NSMutableString* string = [NSMutableString string]; •  The  above  string  is  released  in  Autorelease  Pool!
  • 45. Problem   // Programmer A code [[someObject giveCat] eat]; // Programmer B code - (Cat*) giveCat { // Must be released! Cat* myCat = [[Cat alloc] init]; // But where? Should the programmer who calls this method be // responsible for deallocation of the Cat? How does the programmer // know this? return myCat; } ..
  • 46. Solu)on   // Programmer A code [[someObject giveCat] eat]; // Programmer B code - (Cat*) giveCat { // Must be released! Cat* myCat = [[Cat alloc] init]; // But where? When autopool is drained! [myCat autorelease]; return myCat; }
  • 47. Delayed  Release   •  Autorelease  means  "send  release  message   later".   •  Release  message  is  sent  when  Autorelease   Pool  is  released   •  Autorelease  Pool  is  created  and  released  in   UIKit  programs  automa=cally!   – Pool  is  created  at  the  beginning  of  an  event  cycle   – Pool  is  released  at  the  end  of  an  event  cycle  
  • 48. Autorelease  Pools   App  Loaded   Wait  for  Event   Handle  event   Exit  app   Event  loop   Pool   created   Pool   released  
  • 49. Autorelease  Pool  Usage   // Method - (Cat*) giveCat { // Must be released! Cat* myCat = [[Cat alloc] init]; // But where? When autopool is drained! [myCat autorelease]; return myCat; } // Usage Cat* someCat = [object giveCat]; // someCat will be released in some time, so if you want to hold it, use // retain [someCat retain];
  • 50. Rules   •  If  method  name  contains  "alloc",  "new"  or   "copy",  you  must  remember  to  use  release or  autorelease – Example:  alloc, newObject, mutableCopy •  If  you  retain something,  you  must  use   release or  autorelease •  Instance  Variables:  retain  or  copy   •  autorelease  means  "send  release later"  
  • 51. Cat.h   #import <Foundation/Foundation.h> @interface Cat : NSObject { @private NSString* name; } - (id) initWithName: (NSString*) aName; - (void) setName: (NSString*) aName; - (NSString*) getName; - (void) dealloc; @end
  • 52. Cat.m   #import "Cat.h" @implementation Cat - (id) initWithName: (NSString*) aName { if(self = [super init]) { [self setName: aName]; } return self; } - (NSString*) getName { return name; } - (void) setName: (NSString*) aName { if(aName != name) { [name release]; name = aName; [name retain]; } } - (void) dealloc { [name release]; [super dealloc]; } @end
  • 53. main.m   #import "Cat.h" int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Create the string NSString* catName = [[NSString alloc] initWithString: @"Jack"]; // Create cat with the string Cat* cat = [[Cat alloc] initWithName: catName]; // Just testing. This does not deallocate catName! [catName release]; // Get the name NSString* name = [cat getName]; // Print the name NSLog(name); // Release name and cat [cat release]; [pool drain]; return 0; }  
  • 54. MANAGING  MEMORY  WITH  ARC   ARC  to  the  rescue!  
  • 55. ARC?   •  ARC  (Automa=c  Reference  Coun=ng)   – Compiler  does  automa/c  reference  coun/ng  by   examining  the  source  code  and  then  add  the   retain  and  release  messages  to  objects   •  Not  garbage  collec)on,  no  background   process  of  dealloca)on  of  objects!   •  Inserts  retain  and  release  statements  based   on  some  fixed  rules   •  OS  X  10.7  and  iOS  5  for  all  features  
  • 56. Object  lose  owners   // Scenario 1 Person* jack = [[Person alloc] init]; jack = [[Person alloc] init]; // Scenario 2 Person* tina = [[Person alloc] init]; tina = nil; // Scenario 3 if(yes) { Person* dave = [[Person alloc] init]; }
  • 57. Some  Fixed  rules   •  If  object  is  allocated  and  local  to  method,   release  statement  is  added  near  the  end  of   that  method   •  If  allocated  object  is  class  a@ribute,  release  is   added  to  dealloc   •  If  the  object  is  return  value,  it  gets  an   autorelease  statement  
  • 58. Guidelines   •  Don’t  call!   – retain, release, retainCount, autorelease or dealloc •  You  must  use  @autoreleasepool  syntax   •  You  must  enable  ARC   – clang -fobjc-arc -framework foundation Car.m Motor.m main.m -o App
  • 59. makefile   MyPoint : Car.m Motor.m main.m clang -fobjc-arc -framework foundation Car.m Motor.m main.m -o App run : ./App clean : rm App
  • 71. Property  Declara)on  Aoributes:   Writability   •  You  can  decorate  a  property  with  aoributes,   example:   – @property (readonly) int x; •  readwrite – Indicates  that  the  property  is  read/write.  Default   •  readonly – Only  read   – Generates  only  geoer  method  
  • 72. Seoer  Seman)cs   •  assign –  Simple  seoer.  Default.   •  weak –  Non-­‐owning  rela)onship  with  an  object   –  If  object  is  deallocated,  the  property  is  set  to  nil   •  strong –  Owning  rela)onship  with  an  object   •  copy –  Specifies  that  a  copy  of  the  object  should  be  used  for   assignment  
  • 73. Seoer  Seman)cs  Examples   // assign property = newValue; // copy if (property != newValue) { [property release]; property = [newValue copy]; }
  • 74. Atomicity   •  nonatomic – Specifies  that  accessor  are  non-­‐atomic.     •  Proper)es  are  atomic  by  default:   – [_internal lock]; – id result = [[value retain] autorelease]; – [_internal unlock]; – return id;
  • 78.
  • 80.
  • 82. About  Strings   •  C  String   – char * // Array of characters •  NSString – Object,  that  holds  array  of  Unicode  characters   – Is  immutable,  contents  cannot  be  changed   aLerwards!   •  NSMutableString – String  that  can  be  modified  aLerwards  
  • 83. Crea)ng  Strings   // Simple way NSString *temp1 = @"Hello World!"; // Appending, notice that this produces new string NSString *beginning = @"beginning"; NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"];
  • 84. Formapng   •  Formapng   –  NSString *string1 = [NSString stringWithFormat:@"A string: %@, a float: %1.2f", @"string", 31415.9265]; –  // string1 is "A string: string, a float: 31415.93" •  Format  Specifiers?   – http://developer.apple.com/iphone/ library/documentation/Cocoa/Conceptual/ Strings/Articles/formatSpecifiers.html#// apple_ref/doc/uid/TP40004265-SW1
  • 85. NSString  methods   •  See:   – http://developer.apple.com/documentation/ Cocoa/Reference/Foundation/Classes/ NSString_Class/Reference/NSString.html
  • 86. NSMutableString methods   •  NSMutableString inherites  NSString •  With  NSMutableString you  can  modify  the   string  with  these  methods   – appendFormat: – appendString: – deleteCharactersInRange: – insertString:atIndex: – replaceCharactersInRange:withString: – replaceOccurrencesOfString:withString:options:range: – setString:
  • 88. Protocols?   •  Compared  to  Java,  protocols  are  interfaces   •  You  define  methods  that  some  object  must   implement      
  • 89. Using  Protocols   // MyProtocolName.h // Notice that the protocol inherites NSObject // protocol! @protocol MyProtocolName <NSObject> //Method declarations go here @end // MyObject @interface Class: NSObject <MyProtocolName>  
  • 90. Protocol  as  Variable   •  In  Java   –  MyInterface object = new MyObject(); •  In  Obj-­‐C   –  id<MyProtocolName> object = [[MyObject alloc] init]; •  As  a  method  argument   –  (void) doSomethingWithThisObject: (id<MyProtocolName>) aObject •  ID  is  a  predefined  pointer  type  for  an  arbitrary   object    
  • 92. NSObject   •  NSObject  is  the  root  class  of  Most  Obj-­‐C   classes   •  Crea)ng,  copying,  dealloca)ng  objects    
  • 93. Collec)ons   •  Array:  Ordered  Collec/ons   •  Dic)onary:  Collec/ons  of  Keys  and  Values   •  Set:  Unordered  Collec/ons  of  Objects   •  Counted  Sets:  Unordered  Collec/on  of   Indis/nct  Objects   •  Enumera)on:  Traversing  a  Collec/on's   Elements   •  Mutable  and  immutable  versions!  
  • 94. Other  Classes   •  NSNumber,  wrapper  for  standard  number   types   •  NSDate,  NSCalendarDate