Hey guys, I know there are a lot of questions on this topic already, but it is just not clear to me yet. So, what I am still wondering about is, if I call a method and pass it an object, do I then have to retain this object inside my method to use it there. And if I retain it, where do I release it. Lets make a bit of a more complex example. Could someone explain whats wrong with this:
NSString *myStr = [[NSString alloc]initWithString:@"Hello"];
myStr = [self modString2:[self modString1:myStr]];
[myStr release];
//These are the methods...
-(NSMutableString*)modString1:(NSString*)str{
return [[[str stringByAppendingString:@" Mr. Memory"] mutableCopy] autorelease];
}
-(NSMutableString*)modString2:(NSString*)str{
return [[[str stringByAppendingString:@" How about this?"] mutableCopy] autorelease];
}
This is so confusing to me. Lets assume I create an object inside a method:
[self modString:[self createString]];
-(NSString*)createString{
NSString *string = [NSString stringWithString:@"Hello"];
return string;
}
-(NSMutableString*)modString:(NSString *)str{
[str retain];
NSMutableString *mut = [NSMutableString stringWithString:str];
return mut;
}
Would this be correct? Another thing: If I copy a string from an array into a string like:
NSString *str = [NSString alloc[ initWithString:[[arr objectAtIndex:0]copy]]];
does the retain the whole array, or whats happening here? Would that mean I have to release the array? I dont get it. Are there any practical resources apart from apple`s? I really want to understand this...
A method does not own an object which is getting passed to it as an argument?! Right? And I only would have to retain an object in a method, if the object itself is an object returned by a method (which was called before) with an autorelease via: return [object autorelease] and therefore was created within the method, which was called at first.
And another one:
For example if I do the following:
request = [[NSMutableURLRequest alloc] initWithURL:url];
can I then release the url after this, or does it still have to stick arround for the request to be valid?