Andrew Arrow
Andrew Arrow

Reputation: 4565

Should I call release on these cocoa objective-c variables?

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.

Upvotes: 1

Views: 188

Answers (2)

Felixyz
Felixyz

Reputation: 19143

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

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

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.

Upvotes: 1

Related Questions