So I have the following class. The setName could be called many times for a same data instance. Now the question is, if don’t do the _name = nil; before assigning it a new string (allocated memory), would it cause memory leaks?
// data.h
@interface data : NSObject
{
@private
NSString *_name;
}
@property (strong, nonatomic) NSString *name;
// data.m
@synthesize name = _name;
- (void)setName:(NSString *)name {
_name = nil; // <-- if don't do this, would it end up causing memory leak?
_name = [NSString alloc] initWithString:name;
}
In your particular case, you won’t get a memory leak. This is because of how @synthesize sets up the setter method for you. In the case of a strong property attribute, your setter looks like this:
It basically takes care of the memory management for you. First it retains the newName, before releasing it (incase name and newName are the same, releasing first would crash your app). Then it releases the old name and assigns newName to your _name ivar