1
votes

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

2 Answers

3
votes

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.)

1
votes

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.