Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- When to retain an NSString?
- -forExample:(NSString*)str{
- [str retain];
- //do something
- [str release];
- }
- - (void) forExample: (NSString *)theString {
- // Will need this object later. Stuff it into an ivar and retain it.
- // myString = [theString retain];
- // For NSString, it's actually better to copy, because this
- // could be a _mutable_ string, and it would in fact be best to use
- // the setter for the ivar, which should deal with the memory management:
- [self setMyString:theString];
- // Do things...
- // Don't release.
- }
- - (void) otherExample {
- [myString doYourStringThing];
- // If you don't need the string past this point (which would be slightly
- // unusual -- it leaves an ivar unset) release it and set it to nil.
- // [myString release]; myString = nil;
- // Again, it would be best to use the setter:
- [self setMyString:nil];
- }
- // Generally you keep ivars around until the instance is deallocated,
- // and release them in dealloc
- - (void) dealloc {
- [myString release];
- [super dealloc];
- }
- - (void)myFunction:(NSString *)foo block:(void (^)())callback {
- [foo retain];
- callback();
- // .. do some stuff
- [foo release];
- }
- - (void)myCallingFunction {
- NSString * myVariable = [[NSString alloc] initWithString:@"Test"];
- [self myFunction:myVariable block:^ {
- [myVariable release];
- }];
- }
Add Comment
Please, Sign In to add comment