Guest User

Object ownership in stringWithString and initWithString in NSString

a guest
Feb 28th, 2012
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  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];
Add Comment
Please, Sign In to add comment