2

I'm using NSString in my classes and often need to copy string value to another class. But my question is how should I initialize string in, for example init? (value is class member and the following calls are in init)

value = [NSString stringWithCString:inStrning encoding:NSASCIIStringEncoding];

or

value = [[NSString alloc] initWithCString:inStrning encoding:NSASCIIStringEncoding];

What is the difference here? Does a memory allocated in 1st call released when init finishes? I'm using value as a assign property. Would it be better to use copy?

And what about copying string when I'm passing it to class using some method? Example:

-(id) initWithObjectTypeStr:(NSString*)inTypeStr
{
    ...
    objectTypeStr = [NSString stringWithString:inType];
    //or 
    objectTypeStr = [[NSString alloc] initWithString:inType];
}

objectTypeStr is not defined as property so it has default properties (assign I think).

What is the best practice to use in this case?

1

2 Answers 2

2
[NSString alloc] initWithString:@""]

Gives back a string you own, you will have to release it.

[NSString stringWithString:@""]

Returns an autorelease object that will release and cleaned up by the autoreleasepool.

I would suggest you read the memory management documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that cleared a lot. Apple guides are more readable when I read them with focus on my problem.
The link is unfortunately dead now.
1

The difference is that in this case objectTypeStr = [NSString stringWithString:inType]; objectTypeStr is auto-released and you dont own the object.

Whereas in objectTypeStr = [[NSString alloc] initWithString:inType]; you take ownership of the object since you are allocating it using alloc or new so its your responsibility to release it after its use

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.