Reputation: 125
I have this simple class which I know is ok in terms of memory leaks.
@interface location : NSObject {
NSString *name;
float lat;
float lon;
NSString *subtitle;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *subtitle;
@property (nonatomic, assign) float lat;
@property (nonatomic, assign) float lon;
@end
@implementation location
@synthesize name;
@synthesize lon;
@synthesize lat;
@synthesize subtitle;
-(void)dealloc{
[name release];
[subtitle release];
[super dealloc];
}
@end
There is retain in the @property so i release in the dealloc method. Now, my question is: If I alloc one of the strings in a init method or some other method I create, should I do another release? If so, when?
@implementation location
@synthesize name;
@synthesize lon;
@synthesize lat;
@synthesize subtitle;
-(void) init{
name = [[NSString alloc] init];
}
-(void)dealloc{
[name release]; // IS THIS CORRECT?!
[subtitle release];
[super dealloc];
}
@end
Upvotes: 1
Views: 152
Reputation: 587
Basically you don't need retain here as you are not reatining anything. Your code is same as if all the properties are assigned.
until you don't call self.name, the retain semantics is not applied.
There is a code style which remove that confusion. keep the property name and instance name different and assign instance name to property name at @synthesize.
Like this:
@interface location : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *nameProp;
@end
@implementation location
@synthesize nameProp = name;
Upvotes: 0
Reputation: 17877
If you are assigning value using self.
notation then you should release
(as retain
was called automatically, if you use synthesize
) if your were using alloc + init
approach for creating new object. Example:
NSString *str = [[NSString alloc] init];
self.name = str;
[str release];
If you are assigning value using self.
notation and assigning autoreleased object then you shouldn't retain
and release
. Example:
NSString *str = [NSString string];
self.name = str;
If you are assigning value without self.
prefix then you should not assign autorelease
object and should not release
, you just should alloc + init
object. Example:
NSString *str = [[NSString alloc] init];
name = str;
Or if you want to assign
autoreleased object without self.
prefix then you should retain it. Example:
NSString *str = [NSString string];
name = [str retain];
In dealloc
method you should release objects
if you didn't do that earlier.
Upvotes: 2