tags:

views:

43

answers:

2

Hi,

I've been playing around so much now with ObjC that I feel lost as far as "autoreleasing" is concerned.

in my .h:

NSString *sAStringMember;

in my .m:

-(void) createAString
{
 NSString *sAString = [NSString stringWithString:[dummyCode...get String ffrom some input field for instance]];
 sAStringMember = sAString;
}

Several short questions:

  1. In "createAString:" an autoreleased string "sAString" is created. If sAString is autoreleased (when is this going to happen?), also my member "sAStringMember" will point to an invalid address, correct?

  2. If above assumption is correct, would it be an option to release sAStringMember before assigning sAString to it and then retain it?

  3. Best would be use "copy" to copy sAString to sAStringMember I suppose?

René

+2  A: 

(1) Yes.
(3) Either -retain or -copy is fine.

The best would be using declared property.

@interface Foo : ... {
  NSString* sAStringMember;
}
@property(copy) NSString* sAStringMember;   // or retain.
@end
...
@implementation Foo
@synthesize sAStringMember;
...
-(void) createAString {
  self.sAStringMember = [dummyCode...get String ffrom some input field for instance];
}
-(void)dealloc {
  ...
  [sAStringMember release];
  [super dealloc];
}
@end

(Also, please avoid Hungarian notation.)

KennyTM
Thanks. What's wrong with Hungarian notation?
Krumelur
A: 

Yes if you keep a pointer to an object from somewhere else and keep it you always have to copy or retain it. Retaining is preferred unless you want to modify it because it does not allocate additional memory and is faster.

For your question about when the string is released the only possible answer is: sometime after your function returned.

In many books you can read that it will happen when the next GUI event is processed but this is not for sure. In the function calling sequence every function can open and close it's own autorelease pool.

If a function does a lot of work it can simply create its autorelease pool and free the autorelease registered objects whenever it will.

Lothar