在类中初始化 NSString* 指针的方法 [英] Which way to initialize NSString* pointer in class

查看:44
本文介绍了在类中初始化 NSString* 指针的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的类中使用 NSString 并且经常需要将字符串值复制到另一个类.但我的问题是我应该如何初始化字符串,例如 init?(值是类成员,以下调用在 init 中)

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];

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

这里有什么不同?init 完成时是否释放了在第一个调用中分配的内存?我使用 value 作为 assign 属性.使用copy会更好吗?

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 未定义为属性,因此它具有默认属性(我认为是 assign).

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

在这种情况下使用的最佳做法是什么?

What is the best practice to use in this case?

推荐答案

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

我建议您阅读 内存管理文档.

这篇关于在类中初始化 NSString* 指针的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆