Want more features on Pastebin? Sign Up, it's FREE!
Guest

Object ownership in stringWithString and initWithString in NSString

By: a guest on Feb 28th, 2012  |  syntax: None  |  size: 0.75 KB  |  views: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //header file has appropriate declarations but not included here:
  2. #import "AddressCard.h"
  3.  
  4. @implementation AddressCard;
  5.  
  6. -(NSString *) name
  7. {
  8.    return name;
  9. }
  10.  
  11. //Recommended code:
  12. -(void) setName: (NSString *) theName
  13. {
  14.    [name release]
  15.    name = [[NSString alloc] initWthString: theName];
  16. }
  17.  
  18. //Incorrect code according to Kochan:
  19. -(void) setName: (NSString *) theName
  20. {
  21.    [name release]
  22.    name = [NSString stringWthString: theName];
  23. }
  24.  
  25. //rest of class implementation code snipped
  26. @end
  27.        
  28. -(void) setName: (NSString *) theName
  29. {
  30.    if (theName == name) return; // if they're equal, no need to do anything further
  31.    [name release];
  32.    name = [theName copy];  // sets name to nil if theName is nil
  33. }
  34.        
  35. name = [[NSString stringWithString: theName] retain];
clone this paste RAW Paste Data