任何人都可以告诉我,如果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;
}
0然后种
初始化& 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:我没有使用性质或合成,我还没有得到那么多。
欢呼-gary-
'NSString * newPlanetName = [NSString alloc] init]'只是一个内存泄漏,因为您立即将一个不同的NSString赋值给该变量,并且永远不会释放旧值。 – Chuck 2009-09-09 20:57:21