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-­‐...
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 MyPointrun :...
Compiling	  and	  Running	  TB308POHJUS-L-2:point pohjus$ ls -altotal 32drwxr-xr-x 6 pohjus staff 204 18 Tou 15:32 .drwxr-...
Instan)a)ng	  an	  Object	  // Declare a pointer to the objectMyPoint* point;// Allocate memory for the objectpoint = [MyP...
Instan)a)ng	  an	  Object:	  One	  Liner	  // Allocate and initialize the objectMyPoint* point1 = [[MyPoint alloc] init];
Messages	  (Methods)	             - (void) setX: (int) n;!        method	  type:	          return	  type	     selector	  n...
Messages,	  with	  Two	  Arguments	  Declara=on	     - (void) setXAndY: (int) x: (int) yUsage	     [object setXAndY: 5: 6]...
EXERCISES	  
MEMORY	  MANAGEMENT	  AND	  OBJECT	  LIFECYCLE	  	  
Memory	  Handling	  in	  General	  •  When	  allocate	  something	  it	  must	  be	  released	      –  Memory	  consump)on...
About	  Pointers	  •  int	  a	  =	  5;	        –  Holds	  one	  integer	  value	        –  The	  integer	  is	  stored	  i...
Example	  of	  Memory	  Address	  int main(int argc, char *argv[]){    int a = 5;    // prints 5    NSLog(@"%i", a);    //...
Pointers	  •  Pointer	  is	  a	  variable	  that	  stores	  memory	     address	  •  int	  a;	       –  holds	  integer	  ...
Example	  about	  Pointers	  #import "MyPoint.h"int main(int   argc, char *argv[]){    int a =    5;    // Store   as memo...
What	  is	  the	  result	  now?	  int main(int   argc, char *argv[]){    int a =    5;    // Store   as memory address to ...
What	  is	  the	  result	  now?	  int main(int argc, char *argv[]){    int a = 5;    int *b = &a;    *b = 10;    NSLog(@"%...
Memory	  Areas	  •  Memory	  can	  be	  divided	  into	  three	  categories	     1.  Global	  or	  sta)c	     2.  Stack	  ...
Sta)c	  •  When	  something	  is	  in	  sta)c	  memory,	  its	  there	     all	  the	  )me	  when	  app	  is	  running	  •...
Example	  of	  Sta)c	  Memory	  int thisIsStoredInStaticMemory = 5;int main(int argc, char *argv[]){    static int thisIsA...
Stack	  -­‐	  Memory	  •  Stack	  –	  memoryarea	  is	  usually	  small	  •  If	  you	  put	  too	  much	  "stuff"	  into	 ...
Example	  of	  Stack	  Memory	  int main(int argc, char *argv[]){    int stack1 = 3;    NSLog(@"My number = %i", stack1); ...
Example	  of	  Stack	  Memory	  int main(int argc, char *argv[]){    if(YES)    {        int stack2 = 4;    }    // Does t...
Heap	  -­‐	  Memory	  •  Heap	  –	  memory	  is	  the	  large	  memory	  area	     where	  almost	  all	  of	  the	  objec...
Example	  of	  Heap	  -­‐	  memory	  #import "MyPoint.h"int main(int argc, char *argv[]){    MyPoint* point = [MyPoint all...
Crea)ng	  a	  Object	  •  The	  crea)on	  of	  an	  object	  is	  done	  in	  two	  parts	  •  1)	  Alloca)ng	  memory	   ...
What	  happens	  in	  Memory?	  •  What	  happens	  in	  here?	      –  MyPoint* p = [MyPoint alloc];•  Two	  things!	    ...
Problem?	  #import "MyPoint.h"int main(int argc, char *argv[]){    if(YES)    {          MyPoint* point = [MyPoint alloc];...
Problem?	  #import "MyPoint.h"int main(int argc, char *argv[]){    MyPoint* point = [MyPoint alloc];    point = [MyPoint a...
init-­‐method?	  •  init-­‐method	  is	  implemented	  in	  NSObject•  You	  can	  however	  implement	  your	  own	  init...
Other	  init-­‐methods	  •  Like	  in	  Java	  and	  C++,	  one	  can	  have	  mul)ple	     constructors	  •  In	  Obj-­‐C...
Deallocing	  Object	  and	  Reference	  Count	  •  Rules	  about	  reference	  coun=ng	      –  When	  object	  is	  creat...
Reference	  Count	  Example	  #import <Foundation/Foundation.h>@interface Cat : NSObject{}- (void) printMyRetainCount;@end...
Reference	  Count	  Example	  int main(int argc, char *argv[]){    Cat* myCat = [[Cat alloc] init];    [myCat printMyRetai...
dealloc•  You	  can	  implement	  a	  dealloc	  method	  (void) dealloc{   // Some code   [super dealloc];}
Reference	  Count	  Example	  #import <Foundation/Foundation.h>        int main(int argc, char *argv[])                   ...
Reference	  Count	  Example	  #import <Foundation/Foundation.h>        int main(int argc, char *argv[])                   ...
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	  ob...
Method	  Names	  •  If	  method	  name	  includes	  alloc	  or	  copy,	  it	     returns	  a	  object	  that	  must	  be	 ...
Problem	  // Programmer A code[[someObject giveCat] eat];// Programmer B code- (Cat*) giveCat{    // Must be released!    ...
Solu)on	  // Programmer A code[[someObject giveCat] eat];// Programmer B code- (Cat*) giveCat{    // Must be released!    ...
Delayed	  Release	  •  Autorelease	  means	  "send	  release	  message	     later".	  •  Release	  message	  is	  sent	  w...
Autorelease	  Pools	                                                           Event	  loop	                        Pool	 ...
Autorelease	  Pool	  Usage	  // Method- (Cat*) giveCat{    // Must be released!    Cat* myCat = [[Cat alloc] init];    // ...
Rules	  •  If	  method	  name	  contains	  "alloc",	  "new"	  or	     "copy",	  you	  must	  remember	  to	  use	  release...
Cat.h	  #import <Foundation/Foundation.h>@interface Cat : NSObject{    @private        NSString* name;}-   (id)          i...
Cat.m	  #import "Cat.h"                          - (void) setName: (NSString*) aName                                      ...
main.m	  #import "Cat.h"                                 // Get the name                                                NS...
ARC	  to	  the	  rescue!	  MANAGING	  MEMORY	  WITH	  ARC	  
ARC?	  •  ARC	  (Automa=c	  Reference	  Coun=ng)	     –  Compiler	  does	  automa/c	  reference	  coun/ng	  by	        exa...
Object	  lose	  owners	  // Scenario 1Person* jack = [[Person alloc] init];jack = [[Person alloc] init];// Scenario 2Perso...
Some	  Fixed	  rules	  •  If	  object	  is	  allocated	  and	  local	  to	  method,	     release	  statement	  is	  added	...
Guidelines	  •  Don’t	  call!	      –  retain, release, retainCount, autorelease       or dealloc•  You	  must	  use	  @au...
makefile	  MyPoint : Car.m Motor.m main.m    clang -fobjc-arc -framework foundation Car.m Motor.m main.m-o Apprun :    ./Ap...
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	  aori...
Seoer	  Seman)cs	  •  assign  –  Simple	  seoer.	  Default.	  •  weak  –  Non-­‐owning	  rela)onship	  with	  an	  object	...
Seoer	  Seman)cs	  Examples	  // assignproperty = newValue;// copyif (property != newValue){   [property release];   prope...
Atomicity	  •  nonatomic   –  Specifies	  that	  accessor	  are	  non-­‐atomic.	  	  •  Proper)es	  are	  atomic	  by	  def...
Car.h	  
Motor.h	  
Main.m	  
Change!	  Car.h	  
STRINGS	  
About	  Strings	  •  C	  String	      –  char * // Array of characters•  NSString    –  Object,	  that	  holds	  array	  o...
Crea)ng	  Strings	  // Simple wayNSString *temp1 = @"Hello World!";// Appending, notice that this produces new stringNSStr...
Formapng	  •  Formapng	     –  NSString *string1 = [NSString stringWithFormat:@"A      string: %@, a float: %1.2f", @"stri...
NSString	  methods	  •  See:	      –  http://developer.apple.com/documentation/       Cocoa/Reference/Foundation/Classes/ ...
NSMutableString methods	  •  NSMutableString inherites	  NSString•  With	  NSMutableString you	  can	  modify	  the	     s...
PROTOCOLS	  
Protocols?	  •  Compared	  to	  Java,	  protocols	  are	  interfaces	  •  You	  define	  methods	  that	  some	  object	  m...
Using	  Protocols	  // MyProtocolName.h// Notice that the protocol inherites NSObject// protocol!@protocol MyProtocolName ...
Protocol	  as	  Variable	  •  In	  Java	       –  MyInterface object = new MyObject();•  In	  Obj-­‐C	       –  id<MyProto...
FOUNDATION	  CLASSES	  
NSObject	  •  NSObject	  is	  the	  root	  class	  of	  Most	  Obj-­‐C	       classes	  •  Crea)ng,	  copying,	  dealloca)...
Collec)ons	  •  Array:	  Ordered	  Collec/ons	  •  Dic)onary:	  Collec/ons	  of	  Keys	  and	  Values	  •  Set:	  Unordere...
Other	  Classes	  •  NSNumber,	  wrapper	  for	  standard	  number	     types	  •  NSDate,	  NSCalendarDate	  
Introduction to Objective - C
Introduction to Objective - C
Upcoming SlideShare
Loading in...5
×

Introduction to Objective - C

9,064

Published on

Introduction to Objective-C

Published in: Technology
3 Comments
35 Likes
Statistics
Notes
No Downloads
Views
Total Views
9,064
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
754
Comments
3
Likes
35
Embeds 0
No embeds

No notes for slide

Introduction to Objective - C

  1. 1. Introduc)on  to  Objec)ve-­‐C   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  2. 2. QUICKSTART  
  3. 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  
  4. 4. Class  Declara)on:  MyPoint.h
  5. 5. Class  Implementa)on:  MyPoint.m
  6. 6. Test  the  Class:  main.m
  7. 7. Simple  makefile  MyPoint : MyPoint.m main.m clang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPointrun : ./MyPointclean : rm MyPoint
  8. 8. Compiling  and  Running  TB308POHJUS-L-2:point pohjus$ ls -altotal 32drwxr-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 makefileTB308POHJUS-L-2:point pohjus$ makeclang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPointTB308POHJUS-L-2:point pohjus$ make run./MyPoint2009-05-18 15:32:46.339 MyPoint[8725:807] X = 0 and Y = 02009-05-18 15:32:46.341 MyPoint[8725:807] X = 8 and Y = 7TB308POHJUS-L-2:point pohjus$
  9. 9. Instan)a)ng  an  Object  // Declare a pointer to the objectMyPoint* point;// Allocate memory for the objectpoint = [MyPoint alloc];// Initialize the objectpoint = [point init];
  10. 10. Instan)a)ng  an  Object:  One  Liner  // Allocate and initialize the objectMyPoint* point1 = [[MyPoint alloc] init];
  11. 11. Messages  (Methods)   - (void) setX: (int) n;! method  type:   return  type   selector  name   argument  type   argument   +  =  class  method       name  -­‐  =  object  method    
  12. 12. Messages,  with  Two  Arguments  Declara=on   - (void) setXAndY: (int) x: (int) yUsage   [object setXAndY: 5: 6];Declara=on,  be@er  way   - (void) setX: (int) x andY: (int) yUsage   [object setX: 5 andY: 6];
  13. 13. EXERCISES  
  14. 14. MEMORY  MANAGEMENT  AND  OBJECT  LIFECYCLE    
  15. 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. 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. 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. 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. 19. Example  about  Pointers  #import "MyPoint.h"int main(int argc, char *argv[]){ int a = 5; // Store as 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. 20. What  is  the  result  now?  int main(int argc, char *argv[]){ int a = 5; // Store as 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. 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. 22. Memory  Areas  •  Memory  can  be  divided  into  three  categories   1.  Global  or  sta)c   2.  Stack   3.  Heap  
  23. 23. Sta)c  •  When  something  is  in  sta)c  memory,  its  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. 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. 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. 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. 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. 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. 29. Example  of  Heap  -­‐  memory  #import "MyPoint.h"int main(int argc, char *argv[]){ MyPoint* point = [MyPoint alloc]; //... [point release]; return 0;}
  30. 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. 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. 32. Problem?  #import "MyPoint.h"int main(int argc, char *argv[]){ if(YES) { MyPoint* point = [MyPoint alloc]; } [point release]; return 0;}
  33. 33. Problem?  #import "MyPoint.h"int main(int argc, char *argv[]){ MyPoint* point = [MyPoint alloc]; point = [MyPoint alloc]; [point release]; return 0;}
  34. 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. 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. 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. 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. 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. 39. dealloc•  You  can  implement  a  dealloc  method  (void) dealloc{ // Some code [super dealloc];}
  40. 40. Reference  Count  Example  #import <Foundation/Foundation.h> int main(int argc, char *argv[]) {@interface Cat : NSObject ....{ Cat* mirri = [[Cat alloc] init]; NSString* name; [mirri setName: someName];} // What happens now? [someName release];- (void) setName: (NSString *) theName }@end Since  reference  count  is   0,  dealloca)on  occurs.  @implementation Cat This  means,  that  the  Cat   does  not  have  a  name  - (void) setName: (NSString *) theName anymore.  { name = theName;}@end
  41. 41. Reference  Count  Example  #import <Foundation/Foundation.h> int main(int argc, char *argv[]) {@interface Cat : NSObject ....{ Cat* mirri = [[Cat alloc] init]; NSString* name; [mirri setName: someName];} // What happens now? [someName release];- (void) setName: (NSString *) theName }@end Since  reference  count  is   1,  dealloca)on  does  not  @implementation Cat occur  and  the  Cat  s)ll   has  its  name.  - (void) setName: (NSString *) theName{ [name release]; name = theName; [name retain];}@end
  42. 42. Copying  a  Object  - (void)setName:(NSString *)theName} [name release]; name = [theName copy];}
  43. 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. 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. 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. 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. 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. 48. Autorelease  Pools   Event  loop   Pool   released   Pool   created  App  Loaded   Wait  for  Event   Handle  event   Exit  app  
  49. 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;}// UsageCat* someCat = [object giveCat];// someCat will be released in some time, so if you want to hold it, use// retain[someCat retain];
  50. 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. 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. 52. Cat.m  #import "Cat.h" - (void) setName: (NSString*) aName {@implementation Cat if(aName != name) {- (id) initWithName: (NSString*) aName [name release];{ name = aName; if(self = [super init]) [name retain]; { } [self setName: aName]; } } return self;} - (void) dealloc {- (NSString*) getName [name release];{ [super dealloc]; return name; }} @end
  53. 53. main.m  #import "Cat.h" // Get the name NSString* name = [cat getName];int main(int argc, char *argv[]){ // Print the name NSAutoreleasePool *pool = NSLog(name); [[NSAutoreleasePool alloc] init]; // Release name and cat // Create the string [cat release]; NSString* catName = [[NSString alloc] initWithString: @"Jack"]; [pool drain]; // Create cat with the string return 0; Cat* cat = [[Cat alloc] }   initWithName: catName]; // Just testing. This does not deallocate catName! [catName release];
  54. 54. ARC  to  the  rescue!  MANAGING  MEMORY  WITH  ARC  
  55. 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. 56. Object  lose  owners  // Scenario 1Person* jack = [[Person alloc] init];jack = [[Person alloc] init];// Scenario 2Person* tina = [[Person alloc] init];tina = nil;// Scenario 3if(yes) { Person* dave = [[Person alloc] init];}
  57. 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. 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. 59. makefile  MyPoint : Car.m Motor.m main.m clang -fobjc-arc -framework foundation Car.m Motor.m main.m-o Apprun : ./Appclean : rm App
  60. 60. main.m  
  61. 61. motor.h  
  62. 62. motor.m  
  63. 63. car.h  
  64. 64. car.m  
  65. 65. PROPERTIES  
  66. 66. Objec)ve-­‐C  2.0:  @property
  67. 67. Objec)ve-­‐C  2.0:  @synthesize
  68. 68. Objec)ve-­‐C  2.0:  Dot  Syntax  
  69. 69. Autosynthesize  
  70. 70. Autosynthesize  
  71. 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. 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. 73. Seoer  Seman)cs  Examples  // assignproperty = newValue;// copyif (property != newValue){ [property release]; property = [newValue copy];}
  74. 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;
  75. 75. Car.h  
  76. 76. Motor.h  
  77. 77. Main.m  
  78. 78. Change!  Car.h  
  79. 79. STRINGS  
  80. 80. 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  
  81. 81. Crea)ng  Strings  // Simple wayNSString *temp1 = @"Hello World!";// Appending, notice that this produces new stringNSString *beginning = @"beginning";NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"];
  82. 82. 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
  83. 83. NSString  methods  •  See:   –  http://developer.apple.com/documentation/ Cocoa/Reference/Foundation/Classes/ NSString_Class/Reference/NSString.html
  84. 84. 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:
  85. 85. PROTOCOLS  
  86. 86. Protocols?  •  Compared  to  Java,  protocols  are  interfaces  •  You  define  methods  that  some  object  must   implement      
  87. 87. Using  Protocols  // MyProtocolName.h// Notice that the protocol inherites NSObject// protocol!@protocol MyProtocolName <NSObject> //Method declarations go here@end// MyObject@interface Class: NSObject <MyProtocolName>  
  88. 88. 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    
  89. 89. FOUNDATION  CLASSES  
  90. 90. NSObject  •  NSObject  is  the  root  class  of  Most  Obj-­‐C   classes  •  Crea)ng,  copying,  dealloca)ng  objects    
  91. 91. 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/ons   Elements  •  Mutable  and  immutable  versions!  
  92. 92. Other  Classes  •  NSNumber,  wrapper  for  standard  number   types  •  NSDate,  NSCalendarDate  
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×