任何人都可以告訴我,如果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