Guest User

Untitled

a guest
Aug 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. When to retain an NSString?
  2. -forExample:(NSString*)str{
  3. [str retain];
  4.  
  5. //do something
  6.  
  7. [str release];
  8. }
  9.  
  10. - (void) forExample: (NSString *)theString {
  11. // Will need this object later. Stuff it into an ivar and retain it.
  12. // myString = [theString retain];
  13. // For NSString, it's actually better to copy, because this
  14. // could be a _mutable_ string, and it would in fact be best to use
  15. // the setter for the ivar, which should deal with the memory management:
  16. [self setMyString:theString];
  17.  
  18. // Do things...
  19.  
  20. // Don't release.
  21. }
  22.  
  23. - (void) otherExample {
  24. [myString doYourStringThing];
  25. // If you don't need the string past this point (which would be slightly
  26. // unusual -- it leaves an ivar unset) release it and set it to nil.
  27. // [myString release]; myString = nil;
  28. // Again, it would be best to use the setter:
  29. [self setMyString:nil];
  30. }
  31.  
  32. // Generally you keep ivars around until the instance is deallocated,
  33. // and release them in dealloc
  34. - (void) dealloc {
  35. [myString release];
  36. [super dealloc];
  37. }
  38.  
  39. - (void)myFunction:(NSString *)foo block:(void (^)())callback {
  40. [foo retain];
  41. callback();
  42. // .. do some stuff
  43. [foo release];
  44. }
  45.  
  46. - (void)myCallingFunction {
  47. NSString * myVariable = [[NSString alloc] initWithString:@"Test"];
  48. [self myFunction:myVariable block:^ {
  49. [myVariable release];
  50. }];
  51. }
Add Comment
Please, Sign In to add comment