Please give me some suggestions about how to change a NSString variable.
At my class, I set a member var:
NSString *m_movieName;
...
@property(nonatomic, retain) NSString *m_movieName;
At viewDidLoad method, I assign a default name to this var:
-(void)viewDidLoad{
NSString *s1 = [[NSString alloc] initWithFormat:@"Forrest Gump"];
self.m_movieName = s1;
...
[s1 release];
[super viewDidLoad]
}
At some function, I want to give a new name to this var, so I did like:
-(void)SomeFunc{
NSString *s2 = [[NSString alloc] initWithFormat:@"Brave Heart"];
//[self.movieName release]; // ??????? Should perform here?
self.m_moiveName = s2;
[s2 release];
}
I know, NSString* var is just a pointer to an allocated memory block, and ‘assign’ operation will increment this memory block’s using count. For my situation, should I release m_movieName before assigning a value to it? If I do not release it (via [self.movieName release]), when and where will the previous block be released?
Thanks for your help very much!
No, you have declared your property as
retain, which means your object will retain the properties value. The synthesized (=compiler generated) setter will take care of releasing the old NSString before assigning a new value, so you don’t have to manage this yourself.Be careful when accessing the backing store for the property directly (
m_movieNamein your instance) as bypassing the setter won’t release the current value automatically.