views:

56

answers:

2

In the code below I'm making a new NSString with alloc and initializing it with the contents of some file. Because I'm calling alloc I know it's my responsibility to call release on the string when I'm done. But what about the variables "lines" and "line"? Since the method "componentsSeparatedByString" does not start with the word "new" or "create" can I assume "lines" will be autoreleased? Same question for "line" since "objectAtIndex" also does not start with "new" or "create".

  NSString* buffer = [[NSString alloc] initWithData:[fileManager contentsAtPath:@"/foo"]
                               encoding:NSUTF8StringEncoding];

  NSArray* lines = [buffer componentsSeparatedByString:@"\n"];
  NSString* line = [lines objectAtIndex:5];

  // do something with line

  [buffer release];

So is the code above okay? Or should I be calling "release" on lines and line too? Thanks.

+2  A: 

Yes lines and line will be autoreleased. Remember: you only have to (auto)release if you have explicitly done either of: alloc, retain, copy, new. (Takes some time to start trusting the conventions.)

Felixyz
You forgot new.
JeremyP
@JeremyP: thanks.
Felixyz
+1  A: 

You should not release lines or line. Unless you are planning to use them beyond your function scope. In that case, you should retain them, and then, release them somewhere else.

Pablo Santa Cruz
Retained on behalf of the caller? Generally wrong, unless the method is named accordingly. That case is what autorelease is for.
Peter Hosey
No. I meant retain it if you are planning to use the reference beyond the function scope. I.E. assign the result to a class variable.
Pablo Santa Cruz
Returning it to the caller puts it beyond your function's scope, too. But yeah, you're right about assigning to a static variable.
Peter Hosey