Which way to initialize NSString* pointer in class

我的梦境 提交于 2020-01-04 06:18:49

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/5580294/which-way-to-initialize-nsstring-pointer-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!