dobry
dobry

Reputation: 141

Which way to initialize NSString* pointer in class

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?

Upvotes: 2

Views: 5906

Answers (2)

rckoenes
rckoenes

Reputation: 69469

[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.

Upvotes: 2

visakh7
visakh7

Reputation: 26400

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

Upvotes: 1

Related Questions