【发布时间】:2009-09-09 17:30:47
【问题描述】:
谁能告诉我 NSString 实例变量“planetName”是否需要由我分配/释放(如下例所示)还是在创建/分配类实例时完成?
我的理解是 int 和 float 不需要,但不确定 NSString & NSArray ...
@interface PlanetClass : NSObject {
NSString *planetName;
}
- (NSString *)planetName;
- (void)setPlanetName:(NSString *)value;
@end
像这样……
- (id) init {
[super init];
planetName = [[NSString alloc] init];
return self;
}
- (void) dealloc {
[planetName release];
[super dealloc];
}
** ---------------------------------- ** 编辑:编辑:这是另一个版本 ** ---------------------------------- **
int main(int argc, const char *argv[]) {
// ** Allocated here
PlanetClass *newPlanet_01 = [[PlanetClass alloc] init];
NSString *newPlanetName = [NSString alloc] init];
// ** Set the instance variable pointer here
newPlanetName = @"Jupiter";
[newPlanet_01 setPlanetName:newPlanetName];
// ** Released here
[newPlanet_01 release];
return 0;
}
init 和 dealloc 方法将是这样的 ...
- (id) init {
[super init];
return self;
}
- (void) dealloc {
// Always release the current copy of planetName
// pointed to by the class instance.
[planetName release]
[super dealloc];
}
setPlanetName 方法如下所示...
- (void)setPlanetName:(NSString *)newPlanetName {
if (planetName != newPlanetName) {
[planetName release];
planetName = [newPlanetName copy];
}
}
PS:我没有使用属性或合成,我还没有走到那一步。
干杯-加里-
【问题讨论】:
-
NSString *newPlanetName = [NSString alloc] init]只是内存泄漏,因为您立即将不同的 NSString 分配给变量并且永远不会释放旧值。
标签: objective-c memory