Objective-C对象内存管理 [英] objective-c Object memory management
问题描述
我有一个简单的类,就内存泄漏而言,我知道是可以的.
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
@property中保留了内容,因此我在dealloc方法中释放了它.现在,我的问题是:如果我在init方法或我创建的其他方法中分配了一个字符串,是否应该发布另一个版本?如果是这样,什么时候?
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
推荐答案
如果要使用self.
表示法分配值,则应release
(因为retain
被自动调用,如果使用synthesize
),如果您正在使用alloc + init
方法创建新对象.示例:
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];
如果要使用self.
表示法分配值并分配自动释放的对象,则不应retain
和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;
如果要分配不带self.
前缀的值,则不应分配autorelease
对象,也不应分配release
,而应该分配alloc + init
对象.示例:
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;
或者,如果要使用assign
自动发布的对象而没有self.
前缀,则应保留该对象.示例:
Or if you want to assign
autoreleased object without self.
prefix then you should retain it. Example:
NSString *str = [NSString string];
name = [str retain];
在dealloc
方法中,如果您之前没有这样做,则应该release objects
.
In dealloc
method you should release objects
if you didn't do that earlier.
这篇关于Objective-C对象内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!