我是来自C++世界的开端目标方案家。 我认为,很难理解国家统计局目标提供的记忆管理:
我有以下几类:
@interface User : NSObject
{
NSString* name;
}
@property (nonatomic,retain) NSString* name;
- (id) initWithName: (NSString*) theName;
- (void) release;
@end
@implementation User
@synthesize name
- (id) initWithName: (NSString*) theName
{
if ( self = [super init] )
{
[self setName:theName];
}
return self;
}
- (void) release
{
[name release];
[super release];
}
@end
在考虑以下法典时,我不能理解保留的结果:
NSString* name = [[NSString alloc] initWithCString:/*C string from sqlite3*/];
// (1) name retainCount = 1
User* user = [[User alloc] initWithName:name];
// (2) name retainCount = 2
[whateverMutableArray addObject:user];
// (3) name retainCount = 2
[user release];
// (4) name retainCount = 1
[name release];
// (5) name retainCount = 0
At (4), the retain count of name decreased from 2 to 1. But that s not correct, there is still the instance of user inside the array that points to name ! The retain count of a variable should only decrease when the retain count of a referring variable is 0, that is, when it is dealloced, not released.