开发者

Objective-C memory management: do I have to release what I alloc?

I'm a newbie Objective-C developer (for iPhone development) and I have a question about memory management. my code is just below;

Model1* model = [[Model1 alloc] init]; 
model.username = [[NSString alloc] initWithString:@"ysnky"]; 
[model.username release];  //开发者_运维知识库 is it needed

do I have to release model.username since I alloc?

Model1.h

@interface Model1 : NSObject {
    NSString* username;
}
@property (nonatomic, retain) NSString* username;
@end

Model1.m

@implementation Model1
@synthesize username;

-(void) dealloc {
    [username release];
    [super dealloc];
}
@end


With the code as you have written it, yes, you have to release that string because as you've noticed it's a string you alloc/init'ed and then the property causes an additional retain.

But you could also just do:

model.username = @"ysnky";


First of all please use code tag to wrap your code.

do something like:

model.username = [[NSString alloc] initWithString:@"ysnky"];

is very discouraged you can use isntead:

model.username = @"ysnky"

in this case you don't have to worry about the object release.

But if you want to use

model.username = [[NSString alloc] initWithString:@"ysnky"]; 

the response to your question is NO. You don't need to call

[model.username release]

or to be more precisous your code is wrong, you have to do something like:

Model1* model = [[Model1 alloc] init]; 
NSString *tmpString = [[NSString alloc] initWithString:@"ysnky"] 
model.username = tmpString; 
[tmpString release];

finally I suggest to you to best design your class, you can make better by doing a initializer like:

Model1* model = [[Model1 alloc] initWithUsername:@"skdnaodnsa"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜